Skip to content

[DTensor] Add shard method - #136589

Closed
kwen2501 wants to merge 1 commit into
gh/kwen2501/64/basefrom
gh/kwen2501/64/head
Closed

kwen2501 wants to merge 1 commit into
gh/kwen2501/64/basefrom
gh/kwen2501/64/head

Conversation

@kwen2501

@kwen2501 kwen2501 commented Sep 25, 2024 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

  • -> [DTensor] Add shard method #136589

      Shards a full tensor based on indicated placements, and returns a
      DTensor containing the shard.
    
      Args:
          full_tensor (torch.Tensor): the full tensor to be sharded.
          placements (Sequence[:class:`Placement`]): the placements that
              describes how to place the local tensor on DeviceMesh.
          device_mesh (:class:`DeviceMesh`, optional): DeviceMesh to place the
              DTensor.  Must have same dimension as the number of placements.
              If not specified, would be retrieve from current context.
    
      Returns:
          A :class:`DTensor` object with the shard as its local tensor.
    
      Examples:
          >>> # xdoctest: +SKIP("need world_size and rank")
          >>> device_mesh = dist.init_device_mesh("cuda", (world_size,))
          >>> full_tensor = torch.arange(world_size, device=f"cuda:{rank}")
          >>> placements = [Shard(1)]
          >>> dtensor = DTensor.shard(full_tensor, placements, device_mesh)
    

Use cases:

(i) Distributed state dict:

shape, offset = compute_local_shape_and_global_offset(
full_tensor.shape, local_state.device_mesh, local_state.placements
)
slices = [
slice(cur_offset, cur_offset + cur_shape)
for cur_shape, cur_offset in zip(shape, offset)
]
local_tensor = full_tensor[slices]
# TODO: currently, we cannot handle strided sharding if the dp dimension is not even. For example,
# one of the case that is not yet supported is when placements = (Shard(0), _StridedShard(0, sf=2)).
local_state_dict[key] = DTensor.from_local(
local_tensor,
local_state.device_mesh,
local_state.placements,

(ii) torchchat:
Converting loaded checkpoint into DTensor:
https://github.com/pytorch/torchchat/blob/main/distributed/dtensor_utils.py#L31-L58

(iii) torchao:
Sharding quantized tensor:
pytorch/ao#937

cc @XilunWu @H-Huang @awgu @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 25, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/136589

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 00e91fa with merge base 3bc073d (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added the oncall: distributed Add this issue/PR to distributed oncall triage queue label Sep 25, 2024
kwen2501 added a commit that referenced this pull request Sep 25, 2024
ghstack-source-id: 0d6be93
Pull Request resolved: #136589
@kwen2501 kwen2501 added the release notes: distributed (dtensor) release notes category label Sep 25, 2024
@awgu

awgu commented Sep 25, 2024

Copy link
Copy Markdown
Collaborator

curious what is the difference from distribute_tensor?

@wz337

wz337 commented Sep 25, 2024

Copy link
Copy Markdown
Contributor

Is this for the purpose of trying to avoid the collective in distribute_tensor?

@wz337
wz337 requested a review from wanchaol September 25, 2024 00:22
@kwen2501

Copy link
Copy Markdown
Collaborator Author

IIRC, distribute_tensor would trigger a scatter operation in case of sharding.
The proposed method does not trigger collective operations, i.e. it shards the presented full_tensor locally.

@kwen2501

Copy link
Copy Markdown
Collaborator Author

Is this for the purpose of trying to avoid the collective in distribute_tensor?

Yep

@awgu

awgu commented Sep 25, 2024

Copy link
Copy Markdown
Collaborator

maybe consider adding a kwarg to distribute_tensor then?

@kwen2501

Copy link
Copy Markdown
Collaborator Author

distribute_tensor, as its name suggests, would distribute it :)

@kwen2501

Copy link
Copy Markdown
Collaborator Author

CC: @jerryzh168 @lessw2020

@wz337

wz337 commented Sep 26, 2024

Copy link
Copy Markdown
Contributor

Could I ask if this is for internal use only?

@wanchaol wanchaol left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this method is well defined compare to distribute_tensor, and I think it should not be added as a public API. IMO DCP itself should handle the full state_dict transformation gracefully instead of making this a public API of DTensor.

The reason why it's problematic:

  1. How do you know if the full_tensor on each different process are the same or not? Each process/rank would have different rng seeds, so calling torch.randn on each process could yield totally different tensors that are not semantically meaningful to DTensor (they are not shard). Creating such an API is going to violate single device semantic..
  2. If you know that for sure that the full_tensor when calling this API is replicated, what you really want to do is to DTensor.from_local(full_tensor, [Replicate()]).redistribute(placements=Shard(0). Explicitly annotation to replicated first is required and that's the way to tell that it's full sure replicated. IMO DCP should directly use this when transforming full state_dict to sharded state_dict under the hood.

@kwen2501

kwen2501 commented Sep 26, 2024 •

Copy link
Copy Markdown
Collaborator Author

Thanks @wanchaol.
This is the scenario for the asked API (sorry I should put it up front):

All workers load the same checkpoint (this is a regular checkpoint, not a DCP checkpoint). From that checkpoint, they see the same full tensor. Each worker wants to take a shard of that full tensor and create a DTensor. They want to do it without sending the tensor over the wire.

Is DTensor.from_local(full_tensor, [Replicate()]).redistribute(placements=Shard(0)) the current way to achieve that? If so, I can use it. Thank you for pointing it out.

nit: I had a feeling that saying a full tensor is Replicate is not much different than making one's guarantee before calling the shard method -- they both seem like "oral commitment" :) Unless there are some specific steps the redistribute method would do?

@kwen2501

kwen2501 commented Sep 26, 2024 •

Copy link
Copy Markdown
Collaborator Author

Could I ask if this is for internal use only?

It is internal in the sense that it is only called within the torch.distributed.tensor package.

My goal is to integrate it into the parallelize_module function under an option. If parallelize_module always requires communication, it induces overhead for inference where the problem the communication tries to resolve does not exist.

Does the above make sense to you? @wanchaol @wz337

I am happy to make shard a private method if the above wish is grantable. And the implementation of _shard can take either what @wanchaol suggested or the current one. Open to discussion. Thanks!

@wz337

wz337 commented Sep 27, 2024 •

Copy link
Copy Markdown
Contributor

Thanks @wanchaol. This is the scenario for the asked API (sorry I should put it up front):

All workers load the same checkpoint (this is a regular checkpoint, not a DCP checkpoint). From that checkpoint, they see the same full tensor. Each worker wants to take a shard of that full tensor and create a DTensor. They want to do it without sending the tensor over the wire.

Is DTensor.from_local(full_tensor, [Replicate()]).redistribute(placements=Shard(0)) the current way to achieve that? If so, I can use it. Thank you for pointing it out.

nit: I had a feeling that saying a full tensor is Replicate is not much different than making one's guarantee before calling the shard method -- they both seem like "oral commitment" :) Unless there are some specific steps the redistribute method would do?

I feel like we could utilize distributed_state_dict for this use case without needing to add the additional API. Let me know if this works for your use case:

  1. create model on meta
  2. then parallelize_module
  3. utilize dcp to load the full state dict into tp-lized model created on meta. The util from distributed state dict takes the full tensor and shard it based on DTensor sharding information (named_parameters() from the model return DTensor so we can faithfully shard it). There is no communication because we are calling DTensor from_local here. code pointer: https://github.com/pytorch/pytorch/blob/main/torch/distributed/_state_dict_utils.py#L556-L572

If this works for you, we could check whether there is any gap in 3 today. Also, if this approach works, then we don't need to have a new shard() API from DTensor or somehow let the public API parallelize_module choose between whether to really distribute_tensor or just trunk local tensor, so we could avoid the risks @wanchaol brought up, cuz we really don't know how users are going to use it.

@kwen2501

kwen2501 commented Sep 27, 2024 •

Copy link
Copy Markdown
Collaborator Author

Thanks for the suggestion @wz337 . The workflow would work for large models.

If I may give some feedbacks?

  1. Re the DCP util pointed out:

def _distribute_tensors(
local_state_dict: Dict[str, Any],
keys: List[str],
device: torch.device,
pg: Optional[dist.ProcessGroup] = None,
) -> None:

  • Is it possible to have a signature without pg? (because I don't have one). In fact, it doesn't seem pg is used in this function.
  • If we decompose the util to tensor level, it would be very similar the _shard method proposed. Can we make a sub-function out of it so that the cases I mentioned can use too?
  1. In the DCP util, I see these two lines:

local_state = _local_state[0]
full_tensor = _local_state[1]

  • It seems to assume that the loaded state dict has certain format: meta data ([0]) and the full tensor ([1]). Does that work for generic checkpoints?
  1. I am not sure I can/should ask all users to use meta init and DCP. I believe the tutorial / document of parallelize_module() do not have these requirements. If a user loaded a model regularly, and want to use the PyTorch APIs for TP inference, he/she may be in a dilemma after finding out there is non-optional communication.

  2. In a SPMD world, all users takes certain responsibility. Take the broadcast(tensor, src, ...) API for example. We are concerned that users may give different src value at different ranks. But we are not so concerned that we don't offer this API.

@fegin

fegin commented Sep 27, 2024

Copy link
Copy Markdown
Contributor

@kwen2501
Both 1 and 2 are not issues because these APIs originally are designed for distributed state_dict used only. We can definitely make them more generic.

  1. Users don't need DCP, distributed state_dict is not coupled with DCP. Users can just use torch.save and torch.load and use distributed state_dict to shard. This is how TorchTune's workfload (though TorchTune has not fully been migrated to distributed state_dict).

@wanchaol

Copy link
Copy Markdown
Collaborator

My goal is to integrate it into the parallelize_module function under an option. If parallelize_module always requires communication, it induces overhead for inference where the problem the communication tries to resolve does not exist.

When creating model on meta device and call parallelize_module to the model, there's no communication happened at all as DTensor APIs wouldn't perform communication for meta device tensors. The question here is what are you trying to achieve? Are you trying to make the workflow mentioned by @wz337? If so, I believe the step 1/2 of the workflow already works, the gap might be hide inside 3, and I believe distributed state_dict or DCP when handling full_state_dict to sharded state_dict resharding it could use DTensor.from_local(full_tensor, [Replicate()]).redistribute(placements=Shard(0)) based on the parallelized module sharding info from DTensors. A "full state_dict" that being seen on each rank means that every tensor inside the state_dict they are actually replicated, so I believe explicitly annotate them to replicated is the right way to go. lmk if this make sense @wz337 @fegin

I am not sure I can/should ask all users to use meta init and DCP. I believe the tutorial / document of parallelize_module() do not have these requirements. If a user loaded a model regularly, and want to use the PyTorch APIs for TP inference, he/she may be in a dilemma after finding out there is non-optional communication.

For this I am a bit unsure, we need to always require the initialization communication for training to ensure the numerical correctness, so exposing a option to avoid init communication would be risky (i.e. what if training users use this, we can't guarantee the convergence anymore). I would think that for folks who seriously treat inference and care about initialization time, we should always recommend meta init, as that's the fastest initialization and don't require any model changes for inference either. If user don't care about initialization time, a few additional communications wouldn't matter for them anyways. Our DCP workflow should make sure the meta init load workflow is well supported.

@wz337

wz337 commented Sep 27, 2024

Copy link
Copy Markdown
Contributor

Thanks for the suggestion @wz337 . The workflow would work for large models.

If I may give some feedbacks?

  1. Re the DCP util pointed out:

def _distribute_tensors(
local_state_dict: Dict[str, Any],
keys: List[str],
device: torch.device,
pg: Optional[dist.ProcessGroup] = None,
) -> None:

  • Is it possible to have a signature without pg? (because I don't have one). In fact, it doesn't seem pg is used in this function.
  • If we decompose the util to tensor level, it would be very similar the _shard method proposed. Can we make a sub-function out of it so that the cases I mentioned can use too?
  1. In the DCP util, I see these two lines:

local_state = _local_state[0]
full_tensor = _local_state[1]

  • It seems to assume that the loaded state dict has certain format: meta data ([0]) and the full tensor ([1]). Does that work for generic checkpoints?
  1. I am not sure I can/should ask all users to use meta init and DCP. I believe the tutorial / document of parallelize_module() do not have these requirements. If a user loaded a model regularly, and want to use the PyTorch APIs for TP inference, he/she may be in a dilemma after finding out there is non-optional communication.
  2. In a SPMD world, all users takes certain responsibility. Take the broadcast(tensor, src, ...) API for example. We are concerned that users may give different src value at different ranks. But we are not so concerned that we don't offer this API.

For 1 and 2, sorry if I didn't clarify, I actually don't mean to ask you to directly uses this private _distribute_tensor API directly. The code pointer is just to show how distributed state dict doesn't incur any communication when loading full tensor into parallelized model. You don't have to use DCP in order to be able to utilize it. Loading full tensor into parallelized model is a functionality existed in distributed state dict and you could directly use set_model_state_dict() to access the funcationlity. Here is a test example: https://github.com/pytorch/pytorch/blob/main/test/distributed/_composable/test_composability/test_2d_composability.py#L433-L443

  1. Are we gonna have a tutorial/recipe of how to do distributed inference? If so, even if parallelize_module doesn't require user to always meta init the model, we could clearly state this in the tutorial example and explain what the benefit is and show user the ideal workflow. If users do want to skip communication, then we need to educate them to do meta init, right? Since there is already a way to do this, we don't need to burden the parallelize_module to support such an option.

@kwen2501

kwen2501 commented Sep 28, 2024 •

Copy link
Copy Markdown
Collaborator Author

Thanks @wz337 !

you could directly use set_model_state_dict() to access the funcationlity

Cool! I will give it a try! It should work for TP case.

(For PP + TP, the situation is a little bit different, because I would need to prepare the stage state dict from the full-model state dict, and while doing that, I will do full-tensor to DTensor conversion. That's why I thought a tensor level conversion util would be super helpful. Not a big deal if hard to host it in PyTorch, I can put it in my project.

======= separation line =======

The parallelize_module story is a different one. Let's say a user has the following code:

# Multiple processes run the following code

m = Model()
sd = torch.load("model.pt", mmap=True)
m.load_state_dict(sd)
pm = parallelize_module(m, mesh, plan)

I think this is legit code. And the user has made sure the models are the same across ranks.
But parallelize_module would still send out model copy from rank 0 (IIUC).

@kwen2501

kwen2501 commented Sep 28, 2024 •

Copy link
Copy Markdown
Collaborator Author

If user don't care about initialization time, a few additional communications wouldn't matter for them anyways

Putting aside whether that's true for every user :) what we are faced is a different problem --

we are trying to get some inference-oriented, quantized dtypes to work with the TP stack -- e.g. int8, float8-inference. If the TP stack accepts DTensor from local sharding, what we have to do is simple -- implement some aten.slice ops for those dtypes, then we would be able to use the parallelize_module API. Otherwise, we will have to go a long route to implement collectives (like scatter, broadcast, etc), which is heavy (and maybe difficult too).

This is an example of supporting the above mentioned dtypes with TP:
https://github.com/pytorch/ao/pull/937/files
So far we are not able to use the parallelize_module API. But we'd wish we could use it.

@fegin

fegin commented Sep 30, 2024

Copy link
Copy Markdown
Contributor

@kwen2501

You can do something like this

# Multiple processes run the following code

m = Model()
m = parallelize_module(m, mesh, plan)
sd = torch.load("model.pt", mmap=True)
set_model_state_dict(m, sd, StateDictOptions(full_state_dict=True))

@kwen2501 kwen2501 closed this Oct 1, 2024
@github-actions
github-actions Bot deleted the gh/kwen2501/64/head branch November 3, 2024 02:11
@kwen2501
kwen2501 restored the gh/kwen2501/64/head branch December 7, 2024 00:41
@github-actions
github-actions Bot deleted the gh/kwen2501/64/head branch January 6, 2025 02:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

oncall: distributed Add this issue/PR to distributed oncall triage queue release notes: distributed (dtensor) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants