Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,18 @@ pip install torch==2.7.0 torchvision==0.22.0 --index-url https://download.pytorc

The frozen base models download from HuggingFace on first use: the [CogVideoX-2b](https://huggingface.co/THUDM/CogVideoX-2b) transformer and VAE (about 4 GB) and the [T5-XXL](https://huggingface.co/google/t5-v1_1-xxl) text encoder (about 45 GB, or 9.5 GB with the [fp16 copy](#smaller-t5-download)).

#### Run on Intel GPU (XPU)

Inference also runs on Intel GPUs through PyTorch's XPU backend. Install the XPU build of PyTorch first, which `pip install -e .` then keeps:

``` bash
pip install "torch==2.13.*" torchvision --index-url https://download.pytorch.org/whl/xpu
pip install -e .
python -c "import torch; print(torch.__version__, torch.xpu.is_available())" # 2.13.0+xpu True
```

Pass `device="xpu"` to `TapestryPolicy` in [Run a policy](#run-a-policy). `eval_libero_parallel.py` and the scripts in `scripts/` that run the model use CUDA when it is available, else XPU, and stop with an error when neither is usable; only `eval_teacher_forced.py` and `eval_determinism_at_t.py` fall back to the CPU. `--device` overrides this where a script has that option. The LIBERO evaluator starts one worker per Intel GPU, and `ZE_AFFINITY_MASK` limits them as `CUDA_VISIBLE_DEVICES` does on NVIDIA GPUs. Training is unchanged and has only been run on CUDA.

## Pretrained checkpoint

| Checkpoint | Training data | Cameras and actions | Inference GPU memory |
Expand Down
27 changes: 15 additions & 12 deletions scripts/benchmark_tapestry_fullpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
from tapestry.eval_utils import action_noise_scheduler
from tapestry.models.base import Tapestry
from tapestry.models.unified_model_wrapper import UnifiedModelWrapper
from tapestry.utils.device import default_device


def log(msg: str) -> None:
Expand Down Expand Up @@ -59,9 +60,11 @@ def main() -> None:
p.add_argument("--out", type=Path, default=None)
args = p.parse_args()

if not torch.cuda.is_available():
raise RuntimeError("CUDA required")
dev = torch.device("cuda:0")
dev = default_device()
if dev.type == "cpu":
raise RuntimeError("CUDA or XPU required")
dev = torch.device(dev.type, 0)
acc = getattr(torch, dev.type) # torch.cuda or torch.xpu
torch.manual_seed(7)

cfg = load_cfg(args.cfg)
Expand Down Expand Up @@ -99,9 +102,9 @@ def main() -> None:
video = torch.rand((n_envs, v, 1, 3, img_size, img_size), device=dev, dtype=torch.float32)
text = torch.randn((n_envs, max_seq_len, text_dim), device=dev, dtype=torch.float32)

torch.cuda.empty_cache()
torch.cuda.synchronize(dev)
torch.cuda.reset_peak_memory_stats(dev)
acc.empty_cache()
acc.synchronize(dev)
acc.reset_peak_memory_stats(dev)

lats: list[float] = []
cond_lats: list[float] = []
Expand All @@ -110,16 +113,16 @@ def main() -> None:
log(f"Timing: get_conditioning_dict + forward (n_inf={args.n_inf}, mode={args.inference_mode})")
for i in range(n_total):
kind = "warmup" if i < args.warmup else "measure"
torch.cuda.synchronize(dev)
acc.synchronize(dev)
t0 = time.perf_counter()

torch.cuda.synchronize(dev)
acc.synchronize(dev)
tA = time.perf_counter()
cond = wrapper.get_conditioning_dict(video, text)
torch.cuda.synchronize(dev)
acc.synchronize(dev)
tB = time.perf_counter()
wrapper.forward(cond, sch, num_inference_steps=args.n_inf)
torch.cuda.synchronize(dev)
acc.synchronize(dev)
tC = time.perf_counter()

total_ms = (tC - t0) * 1000.0
Expand All @@ -131,7 +134,7 @@ def main() -> None:
cond_lats.append(cond_ms)
fwd_lats.append(fwd_ms)

pk_alloc_mb = float(torch.cuda.max_memory_allocated(dev)) / 1024.0 / 1024.0
pk_alloc_mb = float(acc.max_memory_allocated(dev)) / 1024.0 / 1024.0

avg = statistics.mean(lats)
med = statistics.median(lats)
Expand All @@ -147,7 +150,7 @@ def main() -> None:
"max_seq_len": max_seq_len,
"num_inference_steps": args.n_inf,
"inference_mode": args.inference_mode,
"device": torch.cuda.get_device_name(dev),
"device": acc.get_device_name(dev),
"torch_version": torch.__version__,
"latency_ms_avg": avg,
"latency_ms_median": med,
Expand Down
27 changes: 15 additions & 12 deletions scripts/benchmark_tapestry_latency.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

from tapestry.eval_utils import action_noise_scheduler
from tapestry.models.decoders.video import CogVideoXDecoder
from tapestry.utils.device import default_device


@dataclass
Expand Down Expand Up @@ -120,16 +121,17 @@ def run(c: Case, cfg: dict[str, Any], n_envs: int, n_inf: int, warmup: int, meas
dec = mk_dec(cfg, c, dev, dtype)
sch = action_noise_scheduler(cfg)
cond, batch = mk_inputs(c, dec, n_envs, dev)
acc = getattr(torch, dev.type) # torch.cuda or torch.xpu

torch.cuda.empty_cache()
torch.cuda.synchronize(device=dev)
torch.cuda.reset_peak_memory_stats(device=dev)
acc.empty_cache()
acc.synchronize(device=dev)
acc.reset_peak_memory_stats(device=dev)

lats: list[float] = []
n_total = warmup + measure
for i in range(n_total):
kind = "warmup" if i < warmup else "measure"
torch.cuda.synchronize(device=dev)
acc.synchronize(device=dev)
t0 = time.perf_counter()
if c.inference_mode == "joint":
out = dec.decode_actions_with_joint_diffusion(
Expand All @@ -148,14 +150,14 @@ def run(c: Case, cfg: dict[str, Any], n_envs: int, n_inf: int, warmup: int, meas
)
else:
raise ValueError(f"Unknown inference_mode: {c.inference_mode}")
torch.cuda.synchronize(device=dev)
acc.synchronize(device=dev)
dt = (time.perf_counter() - t0) * 1000.0
log(f" iter {i+1}/{n_total} ({kind}) {dt:.2f} ms")
if i >= warmup:
lats.append(dt)

pk_alloc_mb = float(torch.cuda.max_memory_allocated(device=dev)) / (1024.0 * 1024.0)
pk_reserved_mb = float(torch.cuda.max_memory_reserved(device=dev)) / (1024.0 * 1024.0)
pk_alloc_mb = float(acc.max_memory_allocated(device=dev)) / (1024.0 * 1024.0)
pk_reserved_mb = float(acc.max_memory_reserved(device=dev)) / (1024.0 * 1024.0)

avg = statistics.mean(lats)
med = statistics.median(lats)
Expand All @@ -165,7 +167,7 @@ def run(c: Case, cfg: dict[str, Any], n_envs: int, n_inf: int, warmup: int, meas
**asdict(c),
"n_envs": n_envs,
"num_inference_steps": n_inf,
"device": torch.cuda.get_device_name(dev),
"device": acc.get_device_name(dev),
"torch_version": torch.__version__,
"latency_ms_avg": avg,
"latency_ms_median": med,
Expand Down Expand Up @@ -197,9 +199,10 @@ def main() -> None:
p.add_argument("--real-vae", action="store_true", help="Load actual CogVideoX-2b VAE (else patched random latents)")
args = p.parse_args()

if not torch.cuda.is_available():
raise RuntimeError("CUDA is required for this benchmark")
dev = torch.device("cuda:0")
dev = default_device()
if dev.type == "cpu":
raise RuntimeError("CUDA or XPU is required for this benchmark")
dev = torch.device(dev.type, 0)
torch.manual_seed(7)

cfg = load_cfg(args.cfg)
Expand All @@ -224,7 +227,7 @@ def main() -> None:
"float16": torch.float16, "bfloat16": torch.bfloat16, "float32": torch.float32,
}[args.dtype]

log(f"Device: {torch.cuda.get_device_name(dev)} torch={torch.__version__}")
log(f"Device: {getattr(torch, dev.type).get_device_name(dev)} torch={torch.__version__}")
log(f"cfg={args.cfg}")
log(f"case: {base}")

Expand Down
3 changes: 2 additions & 1 deletion scripts/eval_determinism_at_t.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
from tapestry.eval_utils import action_noise_scheduler
from tapestry.models.model_loading import load_unified_model, encode_task_text_with_caching
from tapestry.models.unified_model_wrapper import UnifiedModelWrapper
from tapestry.utils.device import default_device


def load_text_emb_from_file(path: str) -> torch.Tensor:
Expand Down Expand Up @@ -87,7 +88,7 @@ def expand_batch(t, n):

@torch.no_grad()
def run(args):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device = default_device()
torch.manual_seed(args.seed)

# Encode (or load) the task text BEFORE building the main model, so T5-xxl
Expand Down
3 changes: 2 additions & 1 deletion scripts/eval_teacher_forced.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
from tapestry.eval_utils import action_noise_scheduler
from tapestry.models.model_loading import load_checkpoint_cpu, load_unified_model, encode_task_text_with_caching
from tapestry.models.unified_model_wrapper import UnifiedModelWrapper
from tapestry.utils.device import default_device


def load_text_emb_from_file(path: str) -> torch.Tensor:
Expand Down Expand Up @@ -109,7 +110,7 @@ def load_chunk(hdf5_path, t_index, normalizer, action_horizon, action_dim, img_s

@torch.no_grad()
def run(args):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device = default_device()
rng = random.Random(args.seed)
torch.manual_seed(args.seed)
ck = load_checkpoint_cpu(args.checkpoint)
Expand Down
4 changes: 3 additions & 1 deletion scripts/policy_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import numpy as np

from tapestry.models.policy import TapestryPolicy
from tapestry.utils.device import gpu_device
from tapestry.utils.libero_utils import build_libero_env


Expand All @@ -22,9 +23,10 @@ def main():
ap.add_argument("--num-inference-steps", type=int, default=1)
ap.add_argument("--t5-override", default=None, help="T5 encoder to load instead of the checkpoint's, e.g. THUDM/CogVideoX-2b for its smaller fp16 copy")
ap.add_argument("--text-cache-dir", default=None, help="keep T5 off the GPU and cache instruction embeddings in this directory")
ap.add_argument("--device", default=None, help="torch device for the policy (default: cuda, else xpu)")
args = ap.parse_args()

policy = TapestryPolicy(args.checkpoint, "cuda", args.num_inference_steps, args.t5_override, args.text_cache_dir)
policy = TapestryPolicy(args.checkpoint, args.device or gpu_device(), args.num_inference_steps, args.t5_override, args.text_cache_dir)
env, task = build_libero_env(args.suite, args.task, img_size=policy.image_size, n_envs=1, init_state_ids=None)
print(f"task: {task}; cameras: {policy.cameras}; chunk: {policy.action_horizon} x {policy.action_dim}")
obs = env.reset()
Expand Down
5 changes: 3 additions & 2 deletions scripts/prepare_release_checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import torch

from tapestry.models.model_loading import load_checkpoint_cpu
from tapestry.utils.device import gpu_device

HF_SOURCES = {"t5-v1_1-xxl": "google/t5-v1_1-xxl", "CogVideoX-2b": "THUDM/CogVideoX-2b"}

Expand Down Expand Up @@ -118,7 +119,7 @@ def main():
ap.add_argument("--output", required=True)
ap.add_argument("--normalizer-stats", default=None, help="stats JSON to embed when the path in the config is not available here")
ap.add_argument("--verify", action="store_true", help="reload the output with TapestryPolicy and run one forward pass")
ap.add_argument("--device", default="cuda", help="device for --verify")
ap.add_argument("--device", default=None, help="device for --verify (default: cuda, else xpu)")
ap.add_argument("--t5-override", default=None, help="for --verify: T5 encoder to load instead of the checkpoint's, e.g. THUDM/CogVideoX-2b for its smaller fp16 copy")
args = ap.parse_args()

Expand All @@ -138,7 +139,7 @@ def main():
print(f"wrote {args.output} ({os.path.getsize(args.output) / 1e9:.2f} GB); normalizer="
f"{None if normalizer is None else normalizer['action_space']}, relative_rotation_actions={relative_rotation_actions}")
if args.verify:
verify(args.output, args.device, args.t5_override)
verify(args.output, args.device or gpu_device(), args.t5_override)


if __name__ == "__main__":
Expand Down
23 changes: 23 additions & 0 deletions tapestry/utils/device.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""Default torch devices: CUDA when available, else an Intel GPU (XPU), and the CPU only where the code allows it."""
import os

import torch


def default_device() -> torch.device:
"""CUDA when available, else XPU (Intel GPU), else the CPU. A device passed explicitly always takes precedence."""
if torch.cuda.is_available():
return torch.device("cuda")
if hasattr(torch, "xpu") and torch.xpu.is_available():
return torch.device("xpu")
return torch.device("cpu")


def gpu_device() -> torch.device:
"""CUDA when available, else XPU (Intel GPU). For code that needs a GPU: raises instead of falling back to the CPU,
so a process pinned to a missing or unusable GPU stops at once."""
device = default_device()
if device.type == "cpu":
raise RuntimeError(f"no usable CUDA or XPU device (CUDA_VISIBLE_DEVICES={os.environ.get('CUDA_VISIBLE_DEVICES')}, "
f"ZE_AFFINITY_MASK={os.environ.get('ZE_AFFINITY_MASK')})")
return device
13 changes: 10 additions & 3 deletions tapestry/utils/parallel_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@
from tqdm import tqdm

from tapestry.eval_utils import action_noise_scheduler, seed_eval, select_tasks
from tapestry.utils.device import gpu_device


class LiberoEvalWorker:
def __init__(self, checkpoint_path, t5_override, img_size, n_envs, n_rollouts_per_task, max_steps, cond_cameraviews,
temporal_agg, action_horizon, action_dim, save_video, execution_horizon, num_inference_steps, seed):
from tapestry.models.unified_model_wrapper import UnifiedModelWrapper

self.policy = UnifiedModelWrapper.from_checkpoint(checkpoint_path, "cuda", t5_override)
self.policy = UnifiedModelWrapper.from_checkpoint(checkpoint_path, gpu_device(), t5_override)
self.noise_scheduler = action_noise_scheduler(self.policy.model.cfg)
self.img_size = img_size
self.n_envs = n_envs
Expand Down Expand Up @@ -74,10 +75,11 @@ def evaluate_task(self, suite, task_no):


def _init_worker(gpus, worker_args):
"""Pin this worker process to its own GPU before CUDA and MuJoCo start, then load the checkpoint."""
"""Pin this worker process to its own GPU before CUDA (or XPU) and MuJoCo start, then load the checkpoint."""
global _worker
gpu = gpus.get()
os.environ["CUDA_VISIBLE_DEVICES"] = gpu
os.environ["ZE_AFFINITY_MASK"] = gpu # the same for Intel GPUs (XPU)
os.environ["MUJOCO_EGL_DEVICE_ID"] = gpu # robosuite's EGL renderer must use the same device
_worker = LiberoEvalWorker(*worker_args)

Expand All @@ -87,9 +89,14 @@ def _evaluate_task(suite, task_no):


def visible_gpus():
"""Physical GPU IDs from CUDA_VISIBLE_DEVICES, or every GPU when it is unset."""
"""Physical GPU IDs from CUDA_VISIBLE_DEVICES, or every GPU when it is unset. Without CUDA, Intel GPUs (XPU)
are used, from ZE_AFFINITY_MASK or all of them."""
if "CUDA_VISIBLE_DEVICES" in os.environ:
return [gpu for gpu in os.environ["CUDA_VISIBLE_DEVICES"].split(",") if gpu]
if torch.cuda.device_count() == 0 and hasattr(torch, "xpu") and torch.xpu.is_available():
if "ZE_AFFINITY_MASK" in os.environ:
return [gpu for gpu in os.environ["ZE_AFFINITY_MASK"].split(",") if gpu]
return [str(i) for i in range(torch.xpu.device_count())]
return [str(i) for i in range(torch.cuda.device_count())]


Expand Down
24 changes: 24 additions & 0 deletions tests/test_libero_eval_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,30 @@ def test_visible_gpus(monkeypatch):
assert parallel_eval.visible_gpus() == ["0", "1", "2"]


def test_visible_gpus_xpu(monkeypatch):
monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
monkeypatch.delenv("ZE_AFFINITY_MASK", raising=False)
monkeypatch.setattr(torch.cuda, "device_count", lambda: 0)
monkeypatch.setattr(torch, "xpu", SimpleNamespace(is_available=lambda: True, device_count=lambda: 2), raising=False)
assert parallel_eval.visible_gpus() == ["0", "1"]
monkeypatch.setenv("ZE_AFFINITY_MASK", "1")
assert parallel_eval.visible_gpus() == ["1"]


def test_worker_without_usable_gpu_stops_before_loading(monkeypatch):
# A worker pinned to a missing or unusable GPU must fail at start, not run the eval on the CPU.
from tapestry.models.unified_model_wrapper import UnifiedModelWrapper

def load(*args):
raise AssertionError("the checkpoint was loaded without a GPU")

monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
monkeypatch.setattr(torch, "xpu", SimpleNamespace(is_available=lambda: False), raising=False)
monkeypatch.setattr(UnifiedModelWrapper, "from_checkpoint", load)
with pytest.raises(RuntimeError, match="no usable CUDA or XPU device"):
parallel_eval.LiberoEvalWorker("unused.pt", None, 2, 5, 10, 10, ["agentview"], False, 4, 7, False, 2, 1, 17)


def run_eval(checkpoint, num_workers, results_file):
return parallel_eval.run_parallel_libero_eval(
checkpoint, None, ["libero_object"], 2, 5, 10, 10, ["agentview"], False,
Expand Down