Skip to content

Commit 5fcb8a0

Browse files
jeffkbkimfacebook-github-bot
authored andcommitted
Implement tensor padding for local shards wrapper (meta-pytorch#3382)
Summary: X-link: pytorch/pytorch#163183 This diff implements the constant padding functionality (aten.constant_pad_nd.default) for `LocalShardsWrapper`. The method applies constant padding to the local shards based on the provided padding specification. Depending on the sharding type (RW, CW), the padding on [left, right, top, bottom] directions will be either applied to the first/last shard, or all local shards. New unit tests cover: - 1D (RW) top/bottom paddings - 2D (CW) left, right, top, bottom paddings - empty shards, number of dimensions > 2 Differential Revision: D82663766
1 parent c26367f commit 5fcb8a0

File tree

2 files changed

+566
-1
lines changed

2 files changed

+566
-1
lines changed

torchrec/distributed/shards_wrapper.py

Lines changed: 209 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
# COPY of the code from torch.distributed._tensor._shards_wrapper - for package compat
1111

12+
import logging
1213
from typing import Any, List, Tuple
1314

1415
import torch
@@ -24,6 +25,7 @@
2425
WriteItemType,
2526
)
2627

28+
logger: logging.Logger = logging.getLogger(__name__)
2729
aten = torch.ops.aten # pyre-ignore[5]
2830

2931

@@ -73,7 +75,7 @@ def __new__(
7375
cat_tensor_shape[1] += shard.size()[1]
7476

7577
# in cases of sharding optimizer rowwise, we calculate total tensor size by "concat" on first tensor dimension
76-
if len(local_shards) > 1 and local_shards[0].ndim == 1: # column-wise sharding
78+
if len(local_shards) > 1 and local_shards[0].ndim == 1: # row-wise sharding
7779
for shard in local_shards[1:]:
7880
cat_tensor_shape[0] += shard.size()[0]
7981

@@ -119,6 +121,7 @@ def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
119121
aten.copy_.default: cls.handle_copy_,
120122
aten.zeros_like.default: cls.handle_zeros_like,
121123
aten.empty_like.default: cls.handle_empty_like,
124+
aten.constant_pad_nd.default: cls.handle_constant_pad_nd,
122125
}
123126

124127
if func in dispatcher:
@@ -279,6 +282,211 @@ def handle_new_empty(args, kwargs):
279282
self_ls.local_offsets(),
280283
)
281284

285+
@staticmethod
286+
# pyre-fixme[3]: Return type must be annotated.
287+
# pyre-fixme[2]: Parameter must be annotated.
288+
def handle_constant_pad_nd(args, kwargs):
289+
"""
290+
Apply constant padding to LocalShardsWrapper.
291+
292+
The padding is based off of the following ideas:
293+
- The resulting wrapper represents the padded version of the logical tensor.
294+
- Each shard is padded based on the sharding type + dimension that is padded.
295+
- For instance, CW shards padded on the left most col will have only padding on the first CW shard.
296+
- Padding the top row will apply to all CW shards.
297+
"""
298+
self_lsw = args[0]
299+
pad_spec = args[1]
300+
pad_value = args[2] if len(args) > 2 else 0.0
301+
logger.info(
302+
f"padding {self_lsw} with {pad_spec} and value: {pad_value}, current shards: {self_lsw.local_shards()} with offsets: {self_lsw.local_offsets()}. tensor storage metadata: {self_lsw.storage_metadata()}"
303+
)
304+
305+
if len(self_lsw.local_shards()) == 0:
306+
raise NotImplementedError(
307+
"Padding empty LocalShardsWrapper is not supported."
308+
)
309+
310+
local_shards = self_lsw.local_shards()
311+
312+
if len(local_shards) == 1:
313+
padded_shard = torch.nn.functional.pad(
314+
local_shards[0], pad_spec, mode="constant", value=pad_value
315+
)
316+
return LocalShardsWrapper([padded_shard], self_lsw.local_offsets())
317+
318+
padded_shards = list(local_shards)
319+
320+
if local_shards[0].ndim == 2:
321+
# 2D Column-wise sharding: [pad_left, pad_right, pad_top, pad_bottom]
322+
if len(pad_spec) == 2:
323+
# Single dimension padding happens on the left most column
324+
pad_spec = pad_spec + [0, 0]
325+
326+
if len(pad_spec) != 4:
327+
raise ValueError(
328+
f"Padding spec must be of length 4 for 2D tensors, got {len(pad_spec)}"
329+
)
330+
331+
pad_left, pad_right, pad_top, pad_bottom = (
332+
pad_spec[0],
333+
pad_spec[1],
334+
pad_spec[2],
335+
pad_spec[3],
336+
)
337+
338+
if pad_top > 0:
339+
padded_shards = [
340+
torch.nn.functional.pad(
341+
shard, [0, 0, pad_top, 0], mode="constant", value=pad_value
342+
)
343+
for shard in padded_shards
344+
]
345+
if pad_bottom > 0:
346+
padded_shards = [
347+
torch.nn.functional.pad(
348+
shard, [0, 0, 0, pad_bottom], mode="constant", value=pad_value
349+
)
350+
for shard in padded_shards
351+
]
352+
if pad_left > 0:
353+
padded_shards[0] = torch.nn.functional.pad(
354+
padded_shards[0],
355+
[pad_left, 0, 0, 0],
356+
mode="constant",
357+
value=pad_value,
358+
)
359+
if pad_right > 0:
360+
padded_shards[-1] = torch.nn.functional.pad(
361+
padded_shards[-1],
362+
[0, pad_right, 0, 0],
363+
mode="constant",
364+
value=pad_value,
365+
)
366+
elif local_shards[0].ndim == 1:
367+
# 1D Row-wise sharding: [pad_top, pad_bottom]
368+
if len(pad_spec) != 2:
369+
raise ValueError(
370+
f"Padding spec must be of length 2 for 1D tensors, got {len(pad_spec)}"
371+
)
372+
pad_top, pad_bottom = pad_spec[0], pad_spec[1]
373+
374+
if pad_top > 0:
375+
padded_shards[0] = torch.nn.functional.pad(
376+
padded_shards[0], [pad_top, 0], mode="constant", value=pad_value
377+
)
378+
if pad_bottom > 0:
379+
padded_shards[-1] = torch.nn.functional.pad(
380+
padded_shards[-1], [0, pad_bottom], mode="constant", value=pad_value
381+
)
382+
else:
383+
raise NotImplementedError(
384+
f"Padding for {local_shards[0].ndim}D tensors is not supported. "
385+
f"Only 1D and 2D tensors are currently supported."
386+
)
387+
388+
# Update offsets and storage metadata
389+
original_storage = self_lsw.storage_metadata()
390+
updated_offsets, updated_storage = LocalShardsWrapper._compute_updated_metadata(
391+
original_storage,
392+
self_lsw.local_offsets(),
393+
pad_spec,
394+
local_shards[0].ndim,
395+
padded_shards,
396+
)
397+
398+
result = LocalShardsWrapper(padded_shards, updated_offsets)
399+
result._storage_meta = updated_storage
400+
return result
401+
402+
@staticmethod
403+
def _compute_updated_metadata(
404+
original_storage: TensorStorageMetadata,
405+
original_offsets: list[torch.Size],
406+
pad_spec: list[int],
407+
ndim: int,
408+
padded_shards: list[torch.Tensor],
409+
) -> tuple[list[tuple[int, ...]], TensorStorageMetadata]:
410+
"""
411+
Compute updated offsets and storage metadata after padding is applied.
412+
413+
Args:
414+
original_storage: Original storage metadata
415+
original_offsets: Original shard offsets
416+
pad_spec: Padding specification
417+
ndim: Number of dimensions (1=RW or 2=CW)
418+
padded_shards: Padded shard tensors
419+
420+
Returns:
421+
Tuple of (updated_offsets, updated_storage_metadata)
422+
"""
423+
if ndim == 1: # 1D RW
424+
pad_top, pad_bottom = pad_spec[0], pad_spec[1]
425+
426+
updated_offsets = []
427+
for i, offset in enumerate(original_offsets):
428+
if i == 0:
429+
# First shard: offset stays the same (absorbs top padding)
430+
updated_offsets.append(tuple(offset))
431+
else:
432+
# Subsequent shards: shift by top padding amount
433+
new_offset = (offset[0] + pad_top,)
434+
updated_offsets.append(new_offset)
435+
436+
new_global_size = torch.Size(
437+
[original_storage.size[0] + pad_top + pad_bottom]
438+
)
439+
440+
elif ndim == 2: # 2D CW
441+
pad_left, pad_right, pad_top, pad_bottom = (
442+
pad_spec[0],
443+
pad_spec[1],
444+
pad_spec[2],
445+
pad_spec[3],
446+
)
447+
448+
updated_offsets = []
449+
for i, offset in enumerate(original_offsets):
450+
row_offset = offset[0]
451+
col_offset = offset[1]
452+
453+
# Top/bottom padding doesn't affect offsets
454+
# Left padding affects column offsets
455+
if i == 0:
456+
# First shard: column offset stays the same (absorbs left padding)
457+
new_2d_offset = (row_offset, col_offset)
458+
else:
459+
# Subsequent shards: shift column offset by left padding amount
460+
new_2d_offset = (row_offset, col_offset + pad_left)
461+
462+
updated_offsets.append(new_2d_offset)
463+
464+
new_global_size = torch.Size(
465+
[
466+
original_storage.size[0] + pad_top + pad_bottom,
467+
original_storage.size[1] + pad_left + pad_right,
468+
]
469+
)
470+
471+
else:
472+
raise NotImplementedError(f"Metadata computation for {ndim}D not supported")
473+
474+
updated_chunks = [
475+
ChunkStorageMetadata(
476+
offsets=torch.Size(offset),
477+
sizes=shard.size(),
478+
)
479+
for offset, shard in zip(updated_offsets, padded_shards)
480+
]
481+
482+
updated_storage = TensorStorageMetadata(
483+
properties=original_storage.properties,
484+
size=new_global_size,
485+
chunks=updated_chunks,
486+
)
487+
488+
return updated_offsets, updated_storage
489+
282490
@property
283491
def device(self) -> torch._C.device: # type: ignore[override]
284492
return (

0 commit comments

Comments
 (0)