MCPcopy Create free account
hub / github.com/Alpha-VLLM/LLaMA2-Accessory / ShardedTensorLoader

Class ShardedTensorLoader

accessory/util/tensor_parallel.py:526–575  ·  view source on GitHub ↗

r"""A helper class to load a tensor parallel sharded tensor and track the loading status (i.e., check if a tensor is loaded with consistent tensor parallel size, check that each shard is loaded only once, and check that all shards are loaded).

Source from the content-addressed store, hash-verified

524
525
526class ShardedTensorLoader:
527 r"""A helper class to load a tensor parallel sharded tensor and track the
528 loading status (i.e., check if a tensor is loaded with consistent tensor
529 parallel size, check that each shard is loaded only once, and check that
530 all shards are loaded).
531 """
532
533 def __init__(
534 self,
535 target: torch.Tensor,
536 num_shards: int,
537 shard_dim: int,
538 mode: str = "set",
539 ) -> None:
540 r"""Initialize a ShardedTensorLoader.
541
542 Args:
543 target (``torch.Tensor``): The target tensor where value shards are
544 loaded into.
545 num_shards (int): Number of expected shards.
546 shard_dim (int): The dimension along which the tensor is sharded.
547 mode (str): Supported options are ``set`` and ``add``. If ``set``,
548 the old value in the target tensor is overrided with the new
549 value. If ``add``, the new value is added to the old value.
550 """
551 self._target = target
552 self._num_shards = num_shards
553 self._shard_dim = shard_dim
554 self._mode = mode
555
556 self._loaded_shards = set()
557
558 def load_shard(self, shard_id: int, value: torch.Tensor) -> None:
559 r"""Load a shard into the target tensor.
560
561 Args:
562 shard_id (int): The shard id of the current value.
563 value (``torch.Tensor``): The value to be loaded.
564 """
565 assert shard_id not in self._loaded_shards
566 assert shard_id >= 0 and shard_id < self._num_shards
567 self._loaded_shards.add(shard_id)
568 tensor_load_shard(self._target, self._shard_dim, self._num_shards,
569 shard_id, value, self._mode)
570
571 def is_complete(self) -> bool:
572 r"""Check if all the shards are loaded to the target tensor."""
573 assert all(x >= 0 and x < self._num_shards
574 for x in self._loaded_shards)
575 return len(self._loaded_shards) == self._num_shards

Calls

no outgoing calls

Tested by

no test coverage detected