diff --git a/README.md b/README.md index 4bd0784..bfd8f06 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/scripts/benchmark_tapestry_fullpath.py b/scripts/benchmark_tapestry_fullpath.py index de69403..b1cb9b0 100644 --- a/scripts/benchmark_tapestry_fullpath.py +++ b/scripts/benchmark_tapestry_fullpath.py @@ -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: @@ -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) @@ -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] = [] @@ -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 @@ -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) @@ -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, diff --git a/scripts/benchmark_tapestry_latency.py b/scripts/benchmark_tapestry_latency.py index ae2affd..2e564fd 100644 --- a/scripts/benchmark_tapestry_latency.py +++ b/scripts/benchmark_tapestry_latency.py @@ -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 @@ -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( @@ -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) @@ -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, @@ -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) @@ -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}") diff --git a/scripts/eval_determinism_at_t.py b/scripts/eval_determinism_at_t.py index 7355496..ea8eefd 100644 --- a/scripts/eval_determinism_at_t.py +++ b/scripts/eval_determinism_at_t.py @@ -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: @@ -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 diff --git a/scripts/eval_teacher_forced.py b/scripts/eval_teacher_forced.py index e931106..c0dd21b 100644 --- a/scripts/eval_teacher_forced.py +++ b/scripts/eval_teacher_forced.py @@ -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: @@ -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) diff --git a/scripts/policy_example.py b/scripts/policy_example.py index 2908f82..6bd256e 100644 --- a/scripts/policy_example.py +++ b/scripts/policy_example.py @@ -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 @@ -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() diff --git a/scripts/prepare_release_checkpoint.py b/scripts/prepare_release_checkpoint.py index 7a19f55..3141e24 100644 --- a/scripts/prepare_release_checkpoint.py +++ b/scripts/prepare_release_checkpoint.py @@ -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"} @@ -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() @@ -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__": diff --git a/tapestry/utils/device.py b/tapestry/utils/device.py new file mode 100644 index 0000000..adceecc --- /dev/null +++ b/tapestry/utils/device.py @@ -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 diff --git a/tapestry/utils/parallel_eval.py b/tapestry/utils/parallel_eval.py index 6f435d9..0868293 100644 --- a/tapestry/utils/parallel_eval.py +++ b/tapestry/utils/parallel_eval.py @@ -12,6 +12,7 @@ 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: @@ -19,7 +20,7 @@ def __init__(self, checkpoint_path, t5_override, img_size, n_envs, n_rollouts_pe 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 @@ -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) @@ -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())] diff --git a/tests/test_libero_eval_selection.py b/tests/test_libero_eval_selection.py index 6aa2e1f..4db217d 100644 --- a/tests/test_libero_eval_selection.py +++ b/tests/test_libero_eval_selection.py @@ -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,