Skip to content

Your first tensor

After installation, save this as first_tensor.py in the source checkout:

first_tensor.py
import tensorcx as cx
device = cx.best_device()
x = cx.ones((1_000_000,), dtype=cx.float32, device=device)
y = cx.ones((1_000_000,), dtype=cx.float32, device=device)
z = x + y
print(z.cpu().numpy()[:5])
# [2. 2. 2. 2. 2.]

Run it in the installed environment:

Terminal window
uv run --no-sync python first_tensor.py

Expected output:

[2. 2. 2. 2. 2.]

best_device() selects an available accelerator, falling back to CPU. Each ones call allocates a contiguous tensor on that device. Addition executes synchronously and returns a new tensor. .cpu().numpy() copies the result to the CPU as needed and returns a NumPy array.

For a reproducible CPU baseline, change device = cx.best_device() to device = "cpu". Constructors without a device argument also default to CPU.

Use cx.devices() to list available devices and cx.is_available("cuda"), cx.is_available("metal") or cx.is_available("vulkan") before selecting an accelerator. Use tensor.to("cuda"), tensor.to("metal") or tensor.to("vulkan") to transfer a tensor explicitly.

CPU, Metal and CUDA currently expose index 0. Vulkan accepts indexed routes such as vulkan:0; only one physical Vulkan GPU has been validated. See the device support matrix and optional Vulkan setup.

Binary operations accept broadcast-compatible shapes with matching dtypes and devices. Use astype to convert dtype explicitly; operations never move inputs between devices. Read tensor operations for the next steps.