Generated banner for Tao Run On Virtualenv
Generated logo for Tao Run On Virtualenv

Tao Run On Virtualenv

NVIDIAOfficialCreated by NVIDIA Corporation

  • Skill
  • Tool integration
  • Automation and integrations
  • Apache-2.0
  • Medium risk
  • Has scripts

From the author

Run a Python training/eval script directly in an existing local virtualenv — no docker, no container. Implements the four-verb consumer contract (submit/status/logs/cancel) over a vendored process-lifecycle runner with durable on-disk state, PID-reuse-safe identity, and process-group cleanup. Use for docker-free local execution, plain-Python model scripts, fast HPO/AutoML trial smokes, or hosts where containers are unavailable. Trigger phrases include "run in my venv", "no docker", "virtualenv execution", "local python training", "run this training script directly".
— the description by NVIDIA Corporation

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The tao-run-on-virtualenv skill provides a mechanism to run Python scripts natively using an existing local virtual environment. It bypasses containerization, making it suitable for environments where Docker is unavailable or for rapid, lightweight experimentation. The skill implements a standard four-verb interface (submit, status, logs, cancel) to manage the lifecycle of local processes, ensuring durable state tracking and process group cleanup.

What it does

  • Executes Python scripts directly using a specified virtualenv interpreter.
  • Manages job lifecycles with submit, status, logs, and cancel operations.
  • Provides durable on-disk state tracking for job records.
  • Ensures process group cleanup to prevent orphaned processes.
  • Supports environment variable injection for secure configuration handling.
  • Integrates with local job recording systems for auditability.

When to use it

  • When running plain Python scripts that do not require containerized environments.
  • When Docker or other container runtimes are unavailable on the host.
  • When minimizing startup overhead for fast HPO or AutoML trial loops.
  • When working on single-node development environments.

Advantages

  • Eliminates container startup latency and dependency management overhead.
  • Operates natively on the host system using existing virtual environments.
  • Provides robust process lifecycle management and cleanup.
  • Supports secure handling of environment variables without exposing them in command arguments.

Usage examples

“Run my training script train.py in the local virtualenv located at /opt/venv.”
The agent initializes the job record, configures the runner to use the specified venv, and launches the training process in a detached state.
“Check the status of my current virtualenv training job.”
The agent queries the runner's durable state files and returns the current status (e.g., RUNNING, COMPLETE, or ERROR).
“Cancel the active training job running in the virtualenv.”
The agent triggers the cancellation process, which uses a durable group guardian to safely terminate the process group.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/nvidia/tao-run-on-virtualenv/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip tao-run-on-virtualenv.zip -d .agents/skills

Documentation by NVIDIA Corporation

Virtualenv — docker-free local Python execution

Standalone install? If this session was not initialized by the TAO skill bank plugin, run the tao-setup skill first (host preflight, credentials, cross-skill discovery).

The virtualenv platform runs a Python script natively in an existing venv — as an argv vector whose first element is <venv>/bin/python, never through a shell, never activating anything. The vendored runner (references/virtualenv_runner.py) is this platform's "native CLI" — the role docker/kubectl/sbatch play elsewhere — and owns only the process lifecycle. Job records stay with tao_job_record.py; specs are authored by the agent, exactly like every other platform.

When to use

  • The workload is a plain Python script (its dependencies pip-installed in a venv), not a TAO container action.

  • No docker on the host, or container startup cost isn't worth it (fast smokes, AutoML trial loops over lightweight models).

  • Single node only. For TAO container actions use tao-run-on-docker; for clusters use -slurm / -kubernetes.

Preflight

# 1. The venv is real and has an executable interpreter.
[ -f "$VENV/pyvenv.cfg" ] && [ -x "$VENV/bin/python" ] || echo "MISSING: $VENV is not a venv"
# 2. The script's top-level imports resolve inside it (catches wrong-venv early);
#    substitute the real modules your script imports.
"$VENV/bin/python" -c "import torch" || echo "MISSING: script dependency not in $VENV"
# 3. GPU visibility only if the script needs CUDA.
nvidia-smi >/dev/null 2>&1 || echo "note: no GPU visible (fine for CPU scripts)"

No credentials are required by the platform itself; model-specific env vars (e.g. HF_TOKEN) pass through by NAME with -e (values never land on argv).

Storage

Tier A by definition — everything is local paths. Datasets must already be on local disk (stage with tao-data-io first if they live in S3). Outputs land in the job record's results_dir, which IS the runner's --job-dir.

Execution — the four verbs

$BANK = ${TAO_SKILL_BANK_PATH}; $RUNNER = $BANK/skills/platform/tao-run-on-virtualenv/references/virtualenv_runner.py.

submit
  1. Author the spec (if the script takes one) at a local path — nested dicts, never flat dotted keys — and lint the assembled command with redact_secrets.py lint.

  2. Open the record — mints the id, binds results_dir BEFORE launch:

    JOB_ID=$("$BANK/scripts/tao_job_record.py" open --platform virtualenv \
      --image "$VENV/bin/python" --network-arch "$ARCH" --action "$ACTION" \
      --storage-tier A --results-root "$RESULTS_ROOT")
    RESULTS_DIR="$RESULTS_ROOT/$JOB_ID"
  3. Launch detached (the runner writes a durable wrapper that gates start, records identity, and cleans up the process group on exit):

    set -a; source /path/to/.env; set +a   # omit if already exported
    python3 "$RUNNER" submit --job-dir "$RESULTS_DIR" --venv "$VENV" \
      --script train.py --job-id "$JOB_ID" --config-path "$SPEC" \
      --arg train --arg=--config={config_path} --arg=--out={results_dir} \
      --gpu-ids 0 -e HF_TOKEN

    Placeholders {config_path} {results_dir} {job_id} render inside --arg tokens. A token starting with - must use the --arg=TOKEN form (argparse). --gpu-ids sets CUDA_VISIBLE_DEVICES; --gpus 0 hides GPUs; neither reserves anything.

  4. Record RUNNING with the pid the runner printed:

    "$BANK/scripts/tao_job_record.py" mark "$JOB_ID" --state RUNNING --backend-ref "pid:<pid>"

One submit per job dir — a retry gets a NEW record (--retry-of), never a re-submit into the same dir.

status
python3 "$RUNNER" status --job-dir "$RESULTS_DIR"   # {"status": "...", ...}

Prints the fixed vocabulary directly: PENDING RUNNING COMPLETE ERROR CANCELED UNKNOWN — no mapping table needed. Status is derived from durable files (exit_status.json, launcher identity) and is safe to poll from any process, any time, including after reboots of the polling agent. On a terminal status, mark the record.

logs
python3 "$RUNNER" logs --job-dir "$RESULTS_DIR" --tail 200
cancel
python3 "$RUNNER" cancel --job-dir "$RESULTS_DIR"
"$BANK/scripts/tao_job_record.py" mark "$JOB_ID" --state CANCELED --source agent

Cancel marks first (a not-yet-started wrapper self-cancels at its start gate), then uses a durable group guardian and Linux pidfds for SIGTERM→SIGKILL. The guardian prevents PGID reuse during discovery; a pidfd pins each target across the observation/signal boundary. already_terminal in the reply means the job finished before the cancel — mark the record with the status it reports instead.

Platform caveats

  • Linux active cancellation. Safe active-process termination requires procfs, pidfd_open, and pidfd_send_signal. On another POSIX host the ps/pgrep fallback can prove a group is empty, but cancellation of active members returns UNKNOWN instead of risking a reused numeric PID or PGID.

  • No multi-node, no image resolution — there is no container. The "image" recorded is the venv's interpreter path.

  • The runner never downloads anything. Remote inputs are the agent's job to stage first (tao-data-io).

Files

references/virtualenv_group_supervisor.py

#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Fail-closed process-group supervision for virtualenv-native jobs.

The caller supplies a durable guardian identity that remains alive in the job
process group for the whole operation.  On Linux, every destructive signal is
sent through a pidfd, never a numeric PID or PGID.  The live guardian prevents
the numeric group id from being reused while members are discovered, and the
pidfds pin each target across the observation/signal boundary.

On another POSIX platform this helper may prove that no target remains, but it
refuses to signal because there is no equivalent kernel-held process handle in
the Python standard library.
"""

from __future__ import annotations

import argparse
import ctypes
import errno
import json
import os
import platform
import select
import signal
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path


class SupervisionError(RuntimeError):
    """The target group could not be observed or signaled safely."""


class OwnershipError(SupervisionError):
    """The durable guardian no longer owns the recorded process group."""


@dataclass(frozen=True)
class ProcFact:
    pid: int
    state: str
    pgid: int
    start_marker: str

    @property
    def active(self) -> bool:
        return self.state != "Z"


def _proc_fact(pid: int, *, proc_root: Path = Path("/proc")) -> ProcFact | None:
    """Read one Linux identity atomically enough to validate a later pidfd.

    ``None`` means the process is gone.  Any other observation failure is
    indeterminate and therefore raises instead of being converted to absence.
    """
    try:
        raw = (proc_root / str(pid) / "stat").read_text(encoding="utf-8")
    except FileNotFoundError:
        return None
    except OSError as exc:
        try:
            os.getpgid(pid)
        except ProcessLookupError:
            return None
        except OSError:
            pass
        raise SupervisionError(f"cannot read /proc/{pid}/stat: {exc}") from exc
    closing = raw.rfind(")")
    if closing < 0:
        raise SupervisionError(f"malformed /proc/{pid}/stat: missing comm terminator")
    fields = raw[closing + 2 :].split()
    if len(fields) <= 19:
        raise SupervisionError(f"malformed /proc/{pid}/stat: truncated fields")
    try:
        return ProcFact(
            pid=pid,
            state=fields[0],
            pgid=int(fields[2]),
            start_marker=fields[19],
        )
    except (TypeError, ValueError) as exc:
        raise SupervisionError(f"malformed /proc/{pid}/stat: invalid fields") from exc


def _linux_group_facts(
    pgid: int, *, proc_root: Path = Path("/proc"),
) -> list[ProcFact]:
    root = proc_root
    try:
        entries = list(root.iterdir())
    except OSError as exc:
        raise SupervisionError(f"cannot enumerate /proc: {exc}") from exc
    facts: list[ProcFact] = []
    for entry in entries:
        if not entry.name.isdigit():
            continue
        pid = int(entry.name)
        try:
            fact = _proc_fact(pid, proc_root=proc_root)
        except SupervisionError:
            # An unreadable unrelated process must not poison an otherwise
            # observable same-UID job.  getpgid is the only safe discriminator.
            try:
                observed_group = os.getpgid(pid)
            except ProcessLookupError:
                continue
            except OSError as exc:
                raise SupervisionError(
                    f"cannot determine whether unreadable process {pid} belongs "
                    f"to process group {pgid}: {exc}"
                ) from exc
            if observed_group != pgid:
                continue
            raise
        if fact is not None and fact.pgid == pgid:
            facts.append(fact)
    return sorted(facts, key=lambda item: item.pid)


def _fallback_group_facts(pgid: int) -> list[ProcFact]:
    """Portable empty-group proof; active members cannot be signaled safely."""
    try:
        found = subprocess.run(
            ["pgrep", "-g", str(pgid)],
            capture_output=True,
            text=True,
            timeout=5,
            env={**os.environ, "LC_ALL": "C", "TZ": "UTC"},
            check=False,
        )
    except Exception as exc:
        raise SupervisionError(f"cannot enumerate process group {pgid}: {exc}") from exc
    if found.returncode == 1:
        return []
    if found.returncode != 0:
        raise SupervisionError(
            f"pgrep failed while enumerating process group {pgid} "
            f"(exit {found.returncode})"
        )
    facts: list[ProcFact] = []
    for token in found.stdout.split():
        if not token.isdigit():
            raise SupervisionError(f"pgrep returned an invalid pid: {token!r}")
        pid = int(token)
        try:
            group = os.getpgid(pid)
        except ProcessLookupError:
            continue
        except OSError as exc:
            raise SupervisionError(f"cannot inspect process {pid}: {exc}") from exc
        if group != pgid:
            continue
        try:
            probed = subprocess.run(
                ["ps", "-p", str(pid), "-o", "stat=", "-o", "lstart="],
                capture_output=True,
                text=True,
                timeout=5,
                env={**os.environ, "LC_ALL": "C", "TZ": "UTC"},
                check=False,
            )
        except Exception as exc:
            raise SupervisionError(f"cannot inspect process {pid}: {exc}") from exc
        text = probed.stdout.strip()
        if probed.returncode != 0 or not text:
            try:
                os.getpgid(pid)
            except ProcessLookupError:
                continue
            except OSError as exc:
                raise SupervisionError(f"cannot inspect process {pid}: {exc}") from exc
            raise SupervisionError(f"state of process {pid} is indeterminate")
        state, _, marker = text.partition(" ")
        facts.append(ProcFact(pid, state, pgid, marker.strip()))
    return sorted(facts, key=lambda item: item.pid)


def group_facts(
    pgid: int, *, proc_root: Path | None = None,
) -> list[ProcFact]:
    if pgid <= 0:
        raise SupervisionError("process-group id must be positive")
    if proc_root is not None:
        return _linux_group_facts(pgid, proc_root=proc_root)
    if Path("/proc/self/stat").is_file():
        return _linux_group_facts(pgid)
    return _fallback_group_facts(pgid)


def _pidfd_capable() -> bool:
    return (
        sys.platform.startswith("linux")
        and (hasattr(os, "pidfd_open") or _pidfd_open_syscall_number() is not None)
        and hasattr(signal, "pidfd_send_signal")
        and Path("/proc/self/stat").is_file()
    )


def _pidfd_open_syscall_number() -> int | None:
    """Linux assigned pidfd_open 434 on the supported TAO architectures.

    Some packaged Python builds omit ``os.pidfd_open`` even when the kernel
    supports it.  Calling the kernel API through libc retains the same
    kernel-held identity guarantee; unknown architectures fail closed.
    """
    machine = platform.machine().lower()
    if machine in {"x86_64", "amd64", "aarch64", "arm64", "riscv64"}:
        return 434
    return None


def _pidfd_open(pid: int) -> int:
    if hasattr(os, "pidfd_open"):
        return os.pidfd_open(pid, 0)
    number = _pidfd_open_syscall_number()
    if number is None:
        raise OSError(errno.ENOSYS, "pidfd_open syscall number is unknown")
    libc = ctypes.CDLL(None, use_errno=True)
    libc.syscall.restype = ctypes.c_long
    fd = int(libc.syscall(number, int(pid), 0))
    if fd < 0:
        error = ctypes.get_errno()
        raise OSError(error, os.strerror(error))
    return fd


def _pidfd_dead(fd: int) -> bool:
    poller = select.poll()
    poller.register(fd, select.POLLIN | select.POLLHUP | select.POLLERR)
    return bool(poller.poll(0))


def _open_verified_pidfd(fact: ProcFact, *, expected_marker: str | None = None) -> int | None:
    """Open a kernel process handle and prove it names the observed identity."""
    if not _pidfd_capable():
        raise SupervisionError(
            "safe signaling requires Linux /proc, pidfd_open support, and "
            "signal.pidfd_send_signal"
        )
    if expected_marker is not None and fact.start_marker != expected_marker:
        raise OwnershipError(
            f"process {fact.pid} start marker no longer matches durable identity"
        )
    try:
        fd = _pidfd_open(fact.pid)
    except ProcessLookupError:
        return None
    except OSError as exc:
        raise SupervisionError(f"cannot open pidfd for process {fact.pid}: {exc}") from exc
    try:
        after = _proc_fact(fact.pid)
        if after is None or _pidfd_dead(fd):
            os.close(fd)
            return None
        if (
            after.pid != fact.pid
            or after.pgid != fact.pgid
            or after.start_marker != fact.start_marker
        ):
            raise OwnershipError(
                f"process {fact.pid} changed identity while its pidfd was opened"
            )
        return fd
    except Exception:
        try:
            os.close(fd)
        except OSError:
            pass
        raise


def _send_pidfd(fd: int, pid: int, sig: int) -> None:
    try:
        signal.pidfd_send_signal(fd, sig, None, 0)
    except ProcessLookupError:
        return
    except PermissionError as exc:
        if _pidfd_dead(fd):
            return
        raise SupervisionError(
            f"permission denied signaling process {pid} through its pidfd"
        ) from exc
    except OSError as exc:
        if _pidfd_dead(fd):
            return
        raise SupervisionError(
            f"failed signaling process {pid} through its pidfd: {exc}"
        ) from exc


def _parse_excludes(values: list[str]) -> dict[int, str]:
    excludes: dict[int, str] = {}
    for value in values:
        pid_text, separator, marker = value.partition(":")
        if not separator or not pid_text.isdigit() or not marker:
            raise SupervisionError(
                f"--exclude must be PID:START_MARKER, got {value!r}"
            )
        excludes[int(pid_text)] = marker
    return excludes


def supervise(
    *,
    pgid: int,
    guardian_pid: int,
    guardian_marker: str,
    excludes: dict[int, str],
    term_timeout: float,
    kill_timeout: float,
) -> dict[str, object]:
    """Terminate every active member except durable, identity-bound excludes."""
    if term_timeout < 0 or kill_timeout < 0:
        raise SupervisionError("timeouts must be non-negative")
    facts = group_facts(pgid)
    guardian = next((item for item in facts if item.pid == guardian_pid), None)
    if guardian is None or not guardian.active:
        raise OwnershipError("durable guardian is gone; refusing group supervision")
    if guardian.pgid != pgid or guardian.start_marker != guardian_marker:
        raise OwnershipError("durable guardian identity no longer owns this group")

    # The guardian is an invariant of this abstraction, not a caller option.
    # Always bind and exclude it even if a future caller omits it from excludes.
    excludes = {**excludes, guardian_pid: guardian_marker}

    if not _pidfd_capable():
        targets = [
            item.pid
            for item in facts
            if item.active
            and not (
                item.pid in excludes
                and excludes[item.pid] == item.start_marker
            )
        ]
        if targets:
            raise SupervisionError(
                "active group members require Linux pidfd supervision; refusing "
                f"to signal numeric pids on {sys.platform}: {targets}"
            )
        return {"result": "empty", "terminated": []}

    guardian_fd = _open_verified_pidfd(guardian, expected_marker=guardian_marker)
    if guardian_fd is None:
        raise OwnershipError("durable guardian exited before supervision started")
    handles: dict[tuple[int, str], int] = {}
    terminated: set[int] = set()

    def close_dead_handles() -> None:
        for identity, fd in list(handles.items()):
            if _pidfd_dead(fd):
                os.close(fd)
                handles.pop(identity, None)
                terminated.add(identity[0])

    def discover() -> int:
        if _pidfd_dead(guardian_fd):
            raise OwnershipError("durable guardian exited during supervision")
        observed = group_facts(pgid)
        if _pidfd_dead(guardian_fd):
            raise OwnershipError("durable guardian exited during group discovery")
        added = 0
        for fact in observed:
            if not fact.active:
                continue
            if fact.pid in excludes and excludes[fact.pid] == fact.start_marker:
                continue
            identity = (fact.pid, fact.start_marker)
            if identity in handles:
                continue
            fd = _open_verified_pidfd(fact)
            if fd is None:
                continue
            if _pidfd_dead(guardian_fd):
                os.close(fd)
                raise OwnershipError("durable guardian exited before target binding")
            handles[identity] = fd
            added += 1
        return added

    try:
        discover()
        for (pid, _), fd in list(handles.items()):
            _send_pidfd(fd, pid, signal.SIGTERM)

        term_deadline = time.monotonic() + term_timeout
        while time.monotonic() < term_deadline:
            close_dead_handles()
            before = set(handles)
            discover()
            for identity, fd in list(handles.items()):
                if identity not in before:
                    _send_pidfd(fd, identity[0], signal.SIGTERM)
            if not handles and discover() == 0:
                return {"result": "terminated", "terminated": sorted(terminated)}
            time.sleep(0.02)

        # Escalation is still pidfd-only.  Repeated discovery catches workers
        # forked during graceful shutdown while the guardian anchors the group.
        kill_deadline = time.monotonic() + kill_timeout
        while True:
            close_dead_handles()
            discover()
            for (pid, _), fd in list(handles.items()):
                _send_pidfd(fd, pid, signal.SIGKILL)
            close_dead_handles()
            if not handles and discover() == 0:
                return {"result": "terminated", "terminated": sorted(terminated)}
            if time.monotonic() >= kill_deadline:
                remaining = sorted({pid for pid, _ in handles})
                raise SupervisionError(
                    f"process group {pgid} still has live members after pidfd "
                    f"SIGKILL: {remaining}"
                )
            time.sleep(0.02)
    finally:
        for fd in handles.values():
            try:
                os.close(fd)
            except OSError:
                pass
        os.close(guardian_fd)


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--pgid", required=True, type=int)
    parser.add_argument("--guardian-pid", required=True, type=int)
    parser.add_argument("--guardian-marker", required=True)
    parser.add_argument("--exclude", action="append", default=[])
    parser.add_argument("--term-timeout", type=float, default=1.0)
    parser.add_argument("--kill-timeout", type=float, default=2.0)
    return parser


def main(argv: list[str] | None = None) -> int:
    args = _parser().parse_args(argv)
    try:
        result = supervise(
            pgid=args.pgid,
            guardian_pid=args.guardian_pid,
            guardian_marker=args.guardian_marker,
            excludes=_parse_excludes(args.exclude),
            term_timeout=args.term_timeout,
            kill_timeout=args.kill_timeout,
        )
    except (OSError, SupervisionError, ValueError) as exc:
        print(json.dumps({"result": "error", "message": str(exc)}, sort_keys=True))
        return 2
    print(json.dumps(result, sort_keys=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Needs Python, Needs Node.js

The author says: Requires a local Python virtualenv (pyvenv.cfg + bin/python) with the training script's dependencies installed. Linux with procfs and pidfd signaling is required for active job cancellation; other POSIX hosts can run jobs and prove empty groups but fail closed rather than signal numeric process IDs. No nvidia-tao-sdk, no docker.

Security

What our scanner noticed· Medium risk

  • Large base64-encoded blobs
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
NVIDIA Corporation
Publisher
NVIDIA (Official)
Source
NVIDIA/skills · skills/tao-run-on-virtualenv · commit fce3cca
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE-APACHE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by NVIDIA Corporation or NVIDIA.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download tao-run-on-virtualenv.zip