Checking CUDA tensor strides, copies and aliases on DGX Spark

Checking CUDA tensor strides, copies and aliases on DGX Spark

Checking CUDA tensor strides, copies and aliases on DGX Spark

A CUDA operator that passes tests with random inputs can still produce incorrect results in a real evaluation pipeline—and floating-point precision is not necessarily to blame. Transposition, blocking and broadcasting can preserve a tensor’s shape while changing how its elements are arranged in storage. If the underlying kernel reads every input as a contiguous array, it may return results for the wrong samples or channels without raising an error.

DGX Spark uses NVIDIA GB10 Grace Blackwell and the ARM64 architecture. The following exercises assume that you have installed and verified a working PyTorch CUDA environment on DGX OS; they do not assume that a particular framework version comes preinstalled. The goal is to use small, deterministic fixtures to establish a repeatable memory layout contract for custom operators.

1. Record shape and layout separately

shape describes the length of each dimension. stride describes how many storage elements you advance when moving by one element along a dimension; it is not measured in bytes. storage_offset gives the offset of the first logical element from the beginning of the underlying storage.

For a two-dimensional tensor, an element’s position is the storage offset plus the row index multiplied by the row stride, plus the column index multiplied by the column stride. The row and column counts alone are not enough to reconstruct that address.

Record the actual environment before starting the tests:

python3 -c 'import platform, torch; assert platform.machine() == "aarch64"; assert torch.cuda.is_available()'
python3 -m torch.utils.collect_env > torch-environment.txt

This record helps trace changes in the framework, runtime libraries and drivers; it is not a performance result. Review the host information it contains before sharing the file.

Document four requirements for the operator under test: supported devices, data types, dimensionality and whether non-contiguous layouts are accepted. If inputs and outputs must not share storage, state that separately as well.

Contiguity, independent storage and numerical correctness are three separate conditions. Satisfying one does not imply either of the others.

2. Use a transpose to expose contiguous-addressing assumptions

Consecutive integers make it easier than random values to spot mixed-up rows and columns. The following transpose leaves the data itself unchanged but changes its logical read order:

import torch

x = torch.arange(12, device="cuda", dtype=torch.float32).reshape(3, 4)
t = x.t()

assert x.stride() == (4, 1)
assert t.shape == (4, 3)
assert t.stride() == (1, 4)
assert not t.is_contiguous()

expected = torch.tensor(
    [[0, 4, 8], [1, 5, 9], [2, 6, 10], [3, 7, 11]],
    device="cuda",
    dtype=torch.float32,
)
torch.testing.assert_close(t, expected, rtol=0, atol=0)

packed = t.contiguous()
assert packed.is_contiguous()
torch.testing.assert_close(packed, expected, rtol=0, atol=0)

When integrating a custom operator, run it with both the original tensor and the transposed tensor, then compare each result with a framework implementation of the same operation. If the operator declares support for contiguous inputs only, the correct outcome for the transpose test is an explicit rejection—not an attempt to return a tensor anyway.

The wrapper can also make the input contiguous explicitly, but that copy must be treated as part of the interface’s behavior. Do not silently copy inputs in correctness tests and then describe the interface as zero-copy in the evaluation report.

3. Check offset slices and reshape copy behavior

Non-contiguous inputs are not the only risk. A tensor can be contiguous while having a nonzero storage offset. Such a tensor is useful for checking whether low-level code incorrectly reads from the beginning of the entire storage allocation:

part = x[1:, :]
assert part.is_contiguous()
assert part.storage_offset() == 4
assert part.data_ptr() == x.data_ptr() + 4 * x.element_size()
assert part[0, 0].item() == 4

flat = t.reshape(-1)
torch.testing.assert_close(
    flat,
    expected.contiguous().view(-1),
    rtol=0,
    atol=0,
)

flat[0] = -99
assert x[0, 0].item() == 0

In this example, the transposed result cannot be represented directly as a one-dimensional contiguous view, so reshape copies the data. The final mutation test confirms that changing the copy does not modify the original tensor. For other layouts, reshape may return a view that shares storage; do not generalize this example into a fixed guarantee.

When writing an extension, also be explicit about the pointer’s origin. A tensor’s data_ptr() already points to its first logical element. Adding storage_offset again would apply the offset twice. If addressing starts at the beginning of the underlying storage instead, the offset must be calculated correctly. These two approaches must not be mixed.

Making a tensor contiguous does not isolate writes

x.contiguous() can return the original tensor when the input is already contiguous. Use clone() when you need to preserve a snapshot of the input. For acceptance testing, modifying the copy and checking that the original values remain unchanged is closer to the actual requirement than checking Python object identity.

4. Do not treat broadcast views as ordinary output buffers

Broadcasting often produces zero strides. Multiple logical positions may point to the same storage element, so correct reads do not imply that element-by-element writes are safe:

row = torch.arange(4, device="cuda", dtype=torch.float32)
expanded = row.unsqueeze(0).expand(3, 4)

assert expanded.stride() == (0, 1)
assert not expanded.is_contiguous()

writable = expanded.clone()
assert writable.is_contiguous()
writable[0, 0] = -1
assert writable[1, 0].item() == 0
assert row[0].item() == 0

For operators that need to write to each element independently, the wrapper should create a fresh output rather than reuse a broadcast view supplied by the caller. If the interface supports only standard contiguous layouts, rejecting non-contiguous outputs at the entry point can reduce the number of overlap cases that need handling.

A contiguous output can still share storage with an input, however. Interfaces that prohibit in-place modification must also check input/output aliasing separately. Comparing two data_ptr() values for equality is not enough: slices with different starting addresses can still overlap in storage.

The conservative approach is to allocate a fresh output in the wrapper and use mutation tests to verify that the input remains untouched. Add dedicated tests for permitted overlap patterns only when in-place execution is actually required.

5. Make layout fixtures an evaluation acceptance gate

Keep four fixed input categories: an ordinary contiguous tensor, a transposed tensor, a contiguous slice with a nonzero offset and a zero-stride broadcast view. Each category needs an explicit outcome: accept it and compute correctly, or reject it before launching the kernel.

The integers in this example are exactly representable, so the assertions use zero tolerance. For real floating-point operations, define absolute and relative tolerances according to the algorithm; do not hide layout errors by loosening thresholds. Check shapes before comparing values, and check data types and devices where necessary so that broadcasting does not let an incorrect result pass.

If a report claims that inputs remain unchanged, save independent snapshots before execution and compare them element by element afterward. If the output will be reused on the next call, save a copy of the first result, run the second call and check whether the earlier result was unintentionally overwritten.

The .item() calls and comparisons in correctness fixtures can trigger synchronization, so they should not be placed directly inside throughput timing regions. Record the cost of making tensors contiguous separately, then decide whether to include it in end-to-end measurements based on the actual call path.

Finally, retain the environment file, fixture code, input layouts and failed assertions. After upgrading the framework or replacing an operator implementation, rerun these small tests before moving on to real models. This makes problems easier to isolate than tracing silent miscomputations after a lengthy evaluation has finished.

Frequently asked questions

Can a custom operator accept a transposed CUDA tensor directly?

Only if its layout contract supports the actual strides. A contiguous-only operator must reject the input or explicitly call contiguous in its wrapper. Arbitrary-stride support needs a transpose test.

Does contiguous always create an independent copy?

No. It may return the original tensor when the input is already contiguous. Use clone when independent storage is required, then mutate the copy and verify that the original stays unchanged.

EPYC 7543P Dedicated Server from $454/month

Configure a CloudVni Dedicated Server Browse AMD Rentals

Dedicated Server Specifications

EPYC 7543P configurations offer 128 GB or 256 GB of memory and direct-attached storage with 2×1 TB NVMe drives.