This tutorial introduces LocalTensor, a powerful debugging tool for developing
and testing distributed tensor operations without requiring multiple processes or GPUs.
What is LocalTensor?
LocalTensor is a torch.Tensor subclass that simulates distributed SPMD
(Single Program, Multiple Data) computations on a single process. It internally
maintains a mapping from rank IDs to their corresponding local tensor shards,
allowing you to debug and test distributed code without infrastructure overhead.
Key Benefits
No Multi-Process Setup Required: Test distributed algorithms on a single CPU/GPU
Faster Debugging Cycles: Iterate quickly without launching multiple processes
Full Visibility: Inspect each rank’s tensor state directly
CI-Friendly: Run distributed tests in single-process CI pipelines
DTensor Integration: Seamlessly test DTensor code locally
Installation and Setup
LocalTensor is part of PyTorch’s distributed package. No additional installation
is required beyond PyTorch itself.
Usage Examples
The following examples demonstrate core patterns for using LocalTensor. Each
example’s code is included directly from source files that are also tested to
ensure correctness. The tests directly invoke these same functions.
Example 1: Basic LocalTensor Creation and Operations
Creating a LocalTensor from per-rank tensors:
defcreate_local_tensor():"""Create a LocalTensor from per-rank tensors. Returns: (local_tensor, (expected_shape, expected_ranks, expected_rank_0, expected_rank_1)) """rank_0_tensor=torch.tensor([[1.0,2.0],[3.0,4.0]])rank_1_tensor=torch.tensor([[5.0,6.0],[7.0,8.0]])local_tensor=LocalTensor({0:rank_0_tensor,1:rank_1_tensor})expected=(torch.Size([2,2]),frozenset({0,1}),rank_0_tensor,rank_1_tensor)returnlocal_tensor,expected
Extracting a tensor when all shards are identical:
defreconcile_identical_shards():"""Extract a single tensor when all shards are identical. Returns: (result, expected) """value=torch.tensor([1.0,2.0,3.0])lt=LocalTensor({0:value.clone(),1:value.clone
Using LocalTensorMode for automatic LocalTensor creation:
Test collective operations like all_reduce, broadcast, and all_gather
without multiple processes.
All-reduce with SUM:
defall_reduce_sum(process_group):"""Simulate all_reduce with SUM across ranks. Returns: (result, expected) """tensors={0:torch.tensor([[
Example 3: Working with DTensor
LocalTensor integrates with DTensor for testing distributed tensor parallelism.
Distribute a tensor and verify reconstruction:
defdistribute_and_verify(world_size:int=4):"""Distribute a tensor and verify reconstruction. Returns: ((sharded_actual, replicated_actual), (sharded_expected, replicated_expected)) """withLocalTensorMode(world_size):mesh=init_device_mesh("cpu"
Example 4: Handling Uneven Sharding
Real-world distributed systems often have uneven data distribution across ranks.
LocalTensor handles this using LocalIntNode.
Creating LocalTensor with different sizes per rank:
defcreate_uneven_shards():"""Create LocalTensor with different sizes per rank. Returns: ((local_tensor, is_symint), expected_shapes_dict) """tensors={0:torch.tensor([[1.0,2.0
Example 5: Rank-Specific Computations
Sometimes you need to perform different operations on different ranks.
Using rank_map() to create per-rank values:
defuse_rank_map(world_size:int=4):"""Create LocalTensors with per-rank values using rank_map. Returns: (values_dict, expected_dict) """withLocalTensorMode(world_size):lt=rank_map(lambdarank:torch
Example 6: Multi-Dimensional Meshes
Use 2D/3D device meshes for hybrid parallelism (e.g., data parallel + tensor parallel).
Creating a 2D mesh:
defcreate_2d_mesh():"""Create a 2D mesh for hybrid parallelism. Returns: ((shape, dim_names, total_size), (expected_shape, expected_names, expected_size)) """world_size=8dp_size,tp_size=4,2withLocalTensorMode(world_size):mesh=init_device_mesh
Testing Tutorial Examples
All examples in this tutorial are tested to ensure correctness. The test suite
directly invokes the same functions included above:
# From test_local_tensor_tutorial_examples.pyfromexample_01_basic_operationsimportcreate_local_tensordeftest_create_local_tensor(self):lt=create_local_tensor()self.assertIsInstance(lt,LocalTensor)self.assertEqual(lt.shape,torch.Size([2,2]))
LocalTensor is a Tensor subclass that simulates a tensor distributed across multiple SPMD
(Single Program, Multiple Data) ranks. Each LocalTensor instance internally holds a mapping from
global rank ids to their corresponding local Tensor shards.Operations performed on a LocalTensor
are applied independently to each local shard, mimicking distributed computation. Collectives
and other distributed operations are handled by mapping them to the local shards as appropriate.
A TorchDispatchMode that simulates SPMD (Single Program, Multiple Data) execution
for LocalTensor objects across a set of ranks.
LocalTensorMode enables PyTorch operations to be transparently applied to each
local shard of a LocalTensor, as if they were distributed across multiple ranks.
When active, this mode intercepts tensor operations and dispatches them to each
rank’s local tensor, collecting and wrapping the results as LocalTensors. It also
handles collective operations by mapping them to local implementations.
This mode is primarily intended for debugging and simulating distributed tensor
computations on a single process, rather than for high-performance distributed
training. It maintains a stack of active modes, patches DeviceMesh coordinate
resolution, and provides utilities for temporarily disabling the mode or mapping
functions over ranks.
disable()
Disables LocalTensorMode temporarily. Primarily is intended to be used to perform
rank specific computations and merge results back before enabling LocalTensorMode back.
Returns the current active LocalTensorMode if one exists.
This function checks the global stack of LocalTensorMode instance. If there
is at least one LocalTensorMode active, it returns the most recently entered
(top of the stack) LocalTensorMode. If no LocalTensorMode is active, it returns None.
Use for Testing Only: LocalTensor has significant overhead and should not
be used in production code.
Initialize Process Groups: Even for local testing, you need to initialize
a process group (use the “fake” backend).
Avoid requires_grad on Inner Tensors: LocalTensor expects inner tensors
to not have requires_grad=True. Set gradients on the LocalTensor wrapper instead.
Reconcile for Assertions: Use reconcile() to extract a single tensor
when all ranks should have identical values (e.g., after an all-reduce).
Debug with Direct Access: Access individual shards via tensor._local_tensors[rank]
for debugging.
Common Pitfalls
Forgetting the Context Manager: Operations on LocalTensor outside
LocalTensorMode still work but won’t create new LocalTensors from factories.
Mismatched Ranks: Ensure all LocalTensors in an operation have compatible ranks.
Inner Tensor Gradients: Creating LocalTensor from tensors with requires_grad=True
will raise an error.
({
0
:
input_0
,
1
:
input_1
})
doubled
=
lt
*
2
added
=
lt
+
10
expected
=
(
input_0
*
2
,
input_1
*
2
,
input_0
+
10
)
return
(
doubled
,
added
),
expected
(),
2
:
value
.
clone
()})
result
=
lt
.
reconcile
()
return
result
,
value
,
LocalTensor
)
num_ranks
=
len
(
x
.
_ranks
)
return
(
is_local
,
num_ranks
),
(
True
,
world_size
)
1.0
,
2.0
],
[
3.0
,
4.0
]]),
1
:
torch
.
tensor
([[
5.0
,
6.0
],
[
7.0
,
8.0
]]),
2
:
torch
.
tensor
([[
9.0
,
10.0
],
[
11.0
,
12.0
]]),
}
expected
=
sum
(
tensors
.
values
())
with
LocalTensorMode
(
frozenset
(
tensors
.
keys
())):
lt
=
LocalTensor
({
k
:
v
.
clone
()
for
k
,
v
in
tensors
.
items
()})
dist
.
all_reduce
(
lt
,
op
=
dist
.
ReduceOp
.
SUM
,
group
=
process_group
)
result
=
lt
.
reconcile
()
return
result
,
expected
Broadcast from a source rank:
defbroadcast_from_rank(process_group,src_rank:int=0):"""Simulate broadcast from a source rank. Returns: (result, expected) """tensors={0:torch.tensor([10.0,20.0,30.0]),1:torch.tensor([40.0,50.0,60.0]),2:torch.tensor([70.0,80.0,90.0]),}expected=tensors[src_rank].clone()withLocalTensorMode(frozenset(tensors.keys())):lt=LocalTensor({k:v.clone()fork,vintensors.items()})dist.broadcast(lt,src=src_rank,group=process_group)result=lt.reconcile()returnresult,expected
All-gather to collect tensors from all ranks:
defall_gather_tensors(process_group):"""Simulate all_gather to collect tensors from all ranks. Returns: (results_list, expected_list) """tensors={0:torch.tensor([[1.0,2.0]]),1:torch.tensor([[3.0,4.0]]),2:torch.tensor([[5.0,6.0]]),}num_ranks=len(tensors)expected=[tensors[i].clone()foriinrange(num_ranks)]withLocalTensorMode(frozenset(tensors.keys())):lt=LocalTensor(tensors)output_list=[torch.zeros_like(lt)for_inrange(num_ranks)]dist.all_gather(output_list,lt,group=process_group)results=[out.reconcile()foroutinoutput_list]returnresults,expected
defhybrid_parallelism():"""Combine data parallel and tensor parallel. Returns: (actual, expected) """world_size=8dp_size,tp_size=4,2withLocalTensorMode(world_size):mesh=init_device_mesh("cpu",(dp_size,tp_size),mesh_dim_names=("dp","tp"))x=torch.randn(16,8)dx=distribute_tensor(x,mesh,[Shard(0),Replicate()])w=torch.randn(8,12)dw=distribute_tensor(w,mesh,[Replicate(),Shard(1)])dy=dx@dwexpected=x@wactual=dy.full_tensor().reconcile()returnactual,expected
3D mesh for DP + TP + PP:
defcreate_3d_mesh():"""Create a 3D mesh for DP + TP + PP. Returns: (actual, expected) """world_size=24pp_size,dp_size,tp_size=2,3,4withLocalTensorMode(world_size):mesh=init_device_mesh("cpu",(pp_size,dp_size,tp_size),mesh_dim_names=("pp","dp","tp"),)tensor=torch.randn(8,16,32)dt=distribute_tensor(tensor,mesh,[Replicate(),Shard(0),Shard(2)])actual=dt.full_tensor().reconcile()returnactual,tensor
Decorator that ensures a function is executed for each local tensor shard
when running under LocalTensorMode. If not in LocalTensorMode, the function
is executed normally. When in LocalTensorMode, the function is run for each
rank, and the results are collected appropriately.
This decorator is useful for functions that exhibit non-SPMD behavior, such
as those requiring rank specific actions. For example, a function that computes
offset into input tensor based on rank.
Note that the function being decorated must not have any side effects and
contain operations for a single rank only. For example, wrapping a function
that performs a collective operation will not work.
Parameters:
func (Callable[..., Any]) – The function to be decorated.
Returns:
The wrapped function that handles LocalTensorMode logic.