Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- _fsdp_api.py +75 -0
- _fsdp_collectives.py +661 -0
- _fsdp_common.py +181 -0
- _fsdp_init.py +242 -0
- _fsdp_param.py +896 -0
- _fsdp_param_group.py +769 -0
- _fsdp_state.py +403 -0
- _fully_shard.py +672 -0
- added_tokens.json +24 -0
- chat_template.jinja +7 -0
- config.json +94 -0
- configuration_llavaonevision1_5.py +288 -0
- generation_config.json +10 -0
- merges.txt +0 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +706 -0
- modeling_llavaonevision1_5.py +0 -0
- preprocessor_config.json +37 -0
- special_tokens_map.json +31 -0
- tokenizer.json +3 -0
- tokenizer_config.json +209 -0
- video_preprocessor_config.json +44 -0
- vocab.json +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
_fsdp_api.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass(frozen=True)
|
| 9 |
+
class MixedPrecisionPolicy:
|
| 10 |
+
"""
|
| 11 |
+
This configures FSDP's mixed precision. Unlike autocast, this applies mixed
|
| 12 |
+
precision at the module level, not op level, which means low-precision
|
| 13 |
+
activations are saved for backward and high-to-low-precision casts are
|
| 14 |
+
incurred only at module boundaries.
|
| 15 |
+
|
| 16 |
+
FSDP works well with module-level mixed precision since it keeps the
|
| 17 |
+
high-precision sharded parameters in memory anyway. In other words, FSDP
|
| 18 |
+
does not require any extra memory to keep a high-precision copy of the
|
| 19 |
+
parameters for the optimizer step.
|
| 20 |
+
|
| 21 |
+
Attributes:
|
| 22 |
+
param_dtype (Optional[torch.dtype]): This specifies the dtype for
|
| 23 |
+
the unsharded parameter and hence the dtype for forward/backward
|
| 24 |
+
computation and the parameter all-gather. If this is ``None``, then
|
| 25 |
+
the unsharded parameter uses the original dtype. The optimizer step
|
| 26 |
+
uses the sharded parameter in the original dtype. (Default:
|
| 27 |
+
``None``)
|
| 28 |
+
reduce_dtype (Optional[torch.dtype]): This specifies the dtype for
|
| 29 |
+
gradient reduction (i.e. reduce-scatter or all-reduce). If this is
|
| 30 |
+
``None`` but ``param_dtype`` is not ``None``, then the reduction
|
| 31 |
+
uses the compute dtype. This can be used to run gradient reduction
|
| 32 |
+
in full precision while using low precision for compute. If also
|
| 33 |
+
gradient reduction is disabled via :meth:`set_requires_gradient_sync`,
|
| 34 |
+
then FSDP will accumulate gradients using ``reduce_dtype``.
|
| 35 |
+
(Default: ``None``)
|
| 36 |
+
output_dtype (Optional[torch.dtype]): This specifies the dtype for
|
| 37 |
+
casting floating-point forward outputs. This can be used to
|
| 38 |
+
help implement cases where different modules have different mixed
|
| 39 |
+
precision policies. (Default: ``None``)
|
| 40 |
+
cast_forward_inputs (bool): This specifies whether FSDP should cast the
|
| 41 |
+
forward's floating-point input tensors to ``param_dtype`` or not.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
param_dtype: Optional[torch.dtype] = None
|
| 45 |
+
reduce_dtype: Optional[torch.dtype] = None
|
| 46 |
+
output_dtype: Optional[torch.dtype] = None
|
| 47 |
+
cast_forward_inputs: bool = True
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass
|
| 51 |
+
class OffloadPolicy:
|
| 52 |
+
"""
|
| 53 |
+
This base class represents the policy of no offloading and is only used as
|
| 54 |
+
the default value for the ``offload_policy`` arg.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class CPUOffloadPolicy(OffloadPolicy):
|
| 60 |
+
"""
|
| 61 |
+
This offload policy offloads parameters, gradients, and optimizer states to
|
| 62 |
+
CPU. Sharded parameters are copied host-to-device before all-gather. The
|
| 63 |
+
all-gathered parameters are freed according to ``reshard_after_forward``.
|
| 64 |
+
Sharded gradients are copied device-to-host in backward, and the optimizer
|
| 65 |
+
step runs on CPU with CPU optimizer states.
|
| 66 |
+
|
| 67 |
+
Attributes:
|
| 68 |
+
pin_memory (bool): Whether to pin sharded parameter and gradient
|
| 69 |
+
memory. Pinning memory allows both more efficient H2D/D2H copies
|
| 70 |
+
and for the copies to overlap with compute. However, the pinned
|
| 71 |
+
memory cannot be used by other processes. Set this to ``False`` if
|
| 72 |
+
you have insufficient CPU memory. (Default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cast, NamedTuple, Optional, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
from torch.distributed.device_mesh import _get_device_handle
|
| 7 |
+
from torch.distributed.distributed_c10d import _resolve_process_group, ReduceOp
|
| 8 |
+
from torch.distributed.tensor import DTensor
|
| 9 |
+
|
| 10 |
+
from ._fsdp_common import (
|
| 11 |
+
_get_dim0_padded_size,
|
| 12 |
+
_raise_assert_with_print,
|
| 13 |
+
_to_dtype_if_needed,
|
| 14 |
+
compiled_autograd_enabled,
|
| 15 |
+
)
|
| 16 |
+
from ._fsdp_param import FSDPParam, ShardedState
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class AllGatherResult(NamedTuple):
|
| 20 |
+
all_gather_output: torch.Tensor
|
| 21 |
+
all_gather_event: Optional[torch.Event]
|
| 22 |
+
all_gather_work: Optional[dist.distributed_c10d.Work]
|
| 23 |
+
# For each parameter, the all-gather input dtype for each input
|
| 24 |
+
param_all_gather_input_dtypes: list[list[torch.dtype]]
|
| 25 |
+
# For each parameter, the all-gather input numel for each input
|
| 26 |
+
param_all_gather_input_numels: list[list[int]]
|
| 27 |
+
# 1D flattened version of `param_all_gather_input_numels` saved to avoid
|
| 28 |
+
# CPU overhead from recomputing
|
| 29 |
+
all_gather_input_split_sizes: list[int]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def allocate_memory(
|
| 33 |
+
size: int,
|
| 34 |
+
dtype: torch.dtype,
|
| 35 |
+
device: torch.device,
|
| 36 |
+
group: dist.ProcessGroup,
|
| 37 |
+
from_process_group: bool,
|
| 38 |
+
) -> torch.Tensor:
|
| 39 |
+
if from_process_group:
|
| 40 |
+
backend = group._get_backend(device)
|
| 41 |
+
if backend.supports_tensor_alloc(device):
|
| 42 |
+
return backend.allocate_tensor(size, dtype=dtype, device=device)
|
| 43 |
+
return torch.empty((size,), dtype=dtype, device=device)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
lib = torch.library.Library("fsdp", "FRAGMENT") # noqa: TOR901
|
| 47 |
+
|
| 48 |
+
lib.define(
|
| 49 |
+
"""
|
| 50 |
+
all_gather_copy_in(
|
| 51 |
+
Tensor[] all_gather_inputs,
|
| 52 |
+
SymInt[] inp_split_sizes,
|
| 53 |
+
SymInt all_gather_input_numel,
|
| 54 |
+
SymInt world_size,
|
| 55 |
+
SymInt rank,
|
| 56 |
+
ScalarType dtype,
|
| 57 |
+
Device device,
|
| 58 |
+
str group_name,
|
| 59 |
+
bool allocate_memory_from_process_group
|
| 60 |
+
) -> (Tensor, Tensor)
|
| 61 |
+
"""
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@torch.library.impl(lib, "all_gather_copy_in", "Meta")
|
| 66 |
+
def all_gather_copy_in_meta(
|
| 67 |
+
all_gather_inputs: list[torch.Tensor],
|
| 68 |
+
inp_split_sizes: list[int],
|
| 69 |
+
all_gather_input_numel: int,
|
| 70 |
+
world_size: int,
|
| 71 |
+
rank: int,
|
| 72 |
+
dtype: torch.dtype,
|
| 73 |
+
device: torch.device,
|
| 74 |
+
group_name: str,
|
| 75 |
+
allocate_memory_from_process_group: bool,
|
| 76 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 77 |
+
all_gather_output = torch.empty(
|
| 78 |
+
(all_gather_input_numel * world_size,), dtype=dtype, device="meta"
|
| 79 |
+
)
|
| 80 |
+
all_gather_input = all_gather_output.narrow(
|
| 81 |
+
0, all_gather_input_numel * rank, all_gather_input_numel
|
| 82 |
+
)
|
| 83 |
+
return all_gather_input, all_gather_output
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@torch.library.impl(lib, "all_gather_copy_in", "CUDA")
|
| 87 |
+
@torch.library.impl(lib, "all_gather_copy_in", "XPU")
|
| 88 |
+
@torch.library.impl(lib, "all_gather_copy_in", "HPU")
|
| 89 |
+
@torch.library.impl(lib, "all_gather_copy_in", "CPU")
|
| 90 |
+
@torch.library.impl(lib, "all_gather_copy_in", "MTIA")
|
| 91 |
+
@torch.library.impl(lib, "all_gather_copy_in", "PrivateUse1")
|
| 92 |
+
def all_gather_copy_in_cuda(
|
| 93 |
+
all_gather_inputs: list[torch.Tensor],
|
| 94 |
+
inp_split_sizes: list[int],
|
| 95 |
+
all_gather_input_numel: int,
|
| 96 |
+
world_size: int,
|
| 97 |
+
rank: int,
|
| 98 |
+
dtype: torch.dtype,
|
| 99 |
+
device: torch.device,
|
| 100 |
+
group_name: str,
|
| 101 |
+
allocate_memory_from_process_group: bool,
|
| 102 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 103 |
+
all_gather_output = allocate_memory(
|
| 104 |
+
all_gather_input_numel * world_size,
|
| 105 |
+
dtype=dtype,
|
| 106 |
+
device=device,
|
| 107 |
+
group=_resolve_process_group(group_name),
|
| 108 |
+
from_process_group=allocate_memory_from_process_group,
|
| 109 |
+
)
|
| 110 |
+
all_gather_input = all_gather_output.narrow(
|
| 111 |
+
0, all_gather_input_numel * rank, all_gather_input_numel
|
| 112 |
+
)
|
| 113 |
+
foreach_copy_dsts = torch.split(all_gather_input, inp_split_sizes)
|
| 114 |
+
with torch.no_grad():
|
| 115 |
+
torch._foreach_copy_(foreach_copy_dsts, all_gather_inputs)
|
| 116 |
+
return all_gather_input, all_gather_output
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
lib.define(
|
| 120 |
+
"split_with_sizes_copy(Tensor all_gather_output, SymInt[] all_gather_input_split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()"
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@torch.library.impl(lib, "split_with_sizes_copy", "Meta")
|
| 125 |
+
@torch.library.impl(lib, "split_with_sizes_copy", "CUDA")
|
| 126 |
+
@torch.library.impl(lib, "split_with_sizes_copy", "XPU")
|
| 127 |
+
@torch.library.impl(lib, "split_with_sizes_copy", "HPU")
|
| 128 |
+
@torch.library.impl(lib, "split_with_sizes_copy", "CPU")
|
| 129 |
+
@torch.library.impl(lib, "split_with_sizes_copy", "MTIA")
|
| 130 |
+
@torch.library.impl(lib, "split_with_sizes_copy", "PrivateUse1")
|
| 131 |
+
def split_with_sizes_copy(
|
| 132 |
+
all_gather_output: torch.Tensor,
|
| 133 |
+
all_gather_input_split_sizes: list[int],
|
| 134 |
+
dim: int,
|
| 135 |
+
out: list[torch.Tensor],
|
| 136 |
+
) -> None:
|
| 137 |
+
torch.split_with_sizes_copy(
|
| 138 |
+
all_gather_output, all_gather_input_split_sizes, dim=dim, out=out
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
lib.define(
|
| 143 |
+
"chunk_cat(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out) -> ()"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@torch.library.impl(lib, "chunk_cat", "Meta")
|
| 148 |
+
@torch.library.impl(lib, "chunk_cat", "CUDA")
|
| 149 |
+
@torch.library.impl(lib, "chunk_cat", "XPU")
|
| 150 |
+
@torch.library.impl(lib, "chunk_cat", "HPU")
|
| 151 |
+
@torch.library.impl(lib, "chunk_cat", "CPU")
|
| 152 |
+
@torch.library.impl(lib, "chunk_cat", "MTIA")
|
| 153 |
+
@torch.library.impl(lib, "chunk_cat", "PrivateUse1")
|
| 154 |
+
def chunk_cat(
|
| 155 |
+
tensors: list[torch.Tensor],
|
| 156 |
+
dim: int,
|
| 157 |
+
num_chunks: int,
|
| 158 |
+
out: torch.Tensor,
|
| 159 |
+
) -> None:
|
| 160 |
+
torch._chunk_cat(tensors, dim, num_chunks, out=out)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@torch.no_grad()
|
| 164 |
+
def foreach_all_gather(
|
| 165 |
+
fsdp_params: list[FSDPParam],
|
| 166 |
+
group: dist.ProcessGroup,
|
| 167 |
+
async_op: bool,
|
| 168 |
+
all_gather_copy_in_stream: torch.Stream,
|
| 169 |
+
all_gather_stream: torch.Stream,
|
| 170 |
+
device: torch.device,
|
| 171 |
+
allocate_memory_from_process_group: bool = False,
|
| 172 |
+
) -> Optional[AllGatherResult]:
|
| 173 |
+
world_size, rank = group.size(), group.rank()
|
| 174 |
+
device_handle = _get_device_handle(device.type)
|
| 175 |
+
with device_handle.stream(all_gather_copy_in_stream):
|
| 176 |
+
param_all_gather_inputs = _get_param_all_gather_inputs(fsdp_params)
|
| 177 |
+
(
|
| 178 |
+
param_all_gather_input_dtypes,
|
| 179 |
+
param_all_gather_input_numels,
|
| 180 |
+
dtype,
|
| 181 |
+
) = _get_all_gather_input_metadatas(param_all_gather_inputs)
|
| 182 |
+
if dtype == torch.uint8:
|
| 183 |
+
all_gather_inputs = [
|
| 184 |
+
t.view(torch.uint8) for ts in param_all_gather_inputs for t in ts
|
| 185 |
+
]
|
| 186 |
+
else:
|
| 187 |
+
all_gather_inputs = [*chain.from_iterable(param_all_gather_inputs)]
|
| 188 |
+
inp_split_sizes = [t.numel() for t in all_gather_inputs]
|
| 189 |
+
all_gather_input_numel = sum(inp_split_sizes)
|
| 190 |
+
all_gather_input, all_gather_output = torch.ops.fsdp.all_gather_copy_in(
|
| 191 |
+
all_gather_inputs,
|
| 192 |
+
inp_split_sizes,
|
| 193 |
+
all_gather_input_numel,
|
| 194 |
+
world_size,
|
| 195 |
+
rank,
|
| 196 |
+
dtype,
|
| 197 |
+
device,
|
| 198 |
+
group.group_name,
|
| 199 |
+
allocate_memory_from_process_group,
|
| 200 |
+
)
|
| 201 |
+
del param_all_gather_inputs
|
| 202 |
+
all_gather_stream.wait_stream(all_gather_copy_in_stream)
|
| 203 |
+
with device_handle.stream(all_gather_stream):
|
| 204 |
+
all_gather_work = dist.all_gather_into_tensor(
|
| 205 |
+
output_tensor=all_gather_output,
|
| 206 |
+
input_tensor=all_gather_input,
|
| 207 |
+
group=group,
|
| 208 |
+
async_op=async_op,
|
| 209 |
+
)
|
| 210 |
+
all_gather_event = all_gather_stream.record_event()
|
| 211 |
+
return AllGatherResult(
|
| 212 |
+
all_gather_output,
|
| 213 |
+
all_gather_event,
|
| 214 |
+
all_gather_work,
|
| 215 |
+
param_all_gather_input_dtypes,
|
| 216 |
+
param_all_gather_input_numels,
|
| 217 |
+
inp_split_sizes,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@torch.no_grad()
|
| 222 |
+
def _get_param_all_gather_inputs(
|
| 223 |
+
fsdp_params: list[FSDPParam],
|
| 224 |
+
) -> list[list[torch.Tensor]]:
|
| 225 |
+
if compiled_autograd_enabled():
|
| 226 |
+
return [fsdp_param.all_gather_inputs for fsdp_param in fsdp_params]
|
| 227 |
+
|
| 228 |
+
# Intentionally try to run a fast-path that bypasses abstractions for the
|
| 229 |
+
# common FSDP case of bf16/fp32 mixed precision in order to use foreach
|
| 230 |
+
# copy for lower CPU overhead and more efficient copying in eager
|
| 231 |
+
def use_foreach_copy(fsdp_param: FSDPParam) -> bool:
|
| 232 |
+
return (
|
| 233 |
+
fsdp_param.param_dtype is not None
|
| 234 |
+
and not fsdp_param.offload_to_cpu
|
| 235 |
+
and not hasattr(fsdp_param._sharded_local_tensor, "fsdp_pre_all_gather")
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
param_all_gather_inputs: list[list[torch.Tensor]] = [[] for _ in fsdp_params]
|
| 239 |
+
foreach_copy_indices: list[int] = []
|
| 240 |
+
foreach_copy_inputs: list[torch.Tensor] = []
|
| 241 |
+
foreach_copy_input_numels: list[int] = []
|
| 242 |
+
|
| 243 |
+
# 1st pass: for foreach-copy parameters, get inputs and metadata for the
|
| 244 |
+
# foreach copy, and for the others, actually get their all-gather inputs
|
| 245 |
+
for i, fsdp_param in enumerate(fsdp_params):
|
| 246 |
+
if use_foreach_copy(fsdp_param):
|
| 247 |
+
foreach_copy_indices.append(i)
|
| 248 |
+
all_gather_input = (
|
| 249 |
+
fsdp_param._sharded_param_data
|
| 250 |
+
if fsdp_param.sharded_state == ShardedState.SHARDED
|
| 251 |
+
else cast(torch.Tensor, fsdp_param._sharded_post_forward_param_data)
|
| 252 |
+
)
|
| 253 |
+
foreach_copy_inputs.append(all_gather_input)
|
| 254 |
+
foreach_copy_input_numels.append(all_gather_input.numel())
|
| 255 |
+
else:
|
| 256 |
+
param_all_gather_inputs[i] = fsdp_param.all_gather_inputs
|
| 257 |
+
|
| 258 |
+
# 2nd pass: use foreach copy to compute the remaining all-gather inputs
|
| 259 |
+
if foreach_copy_inputs:
|
| 260 |
+
fsdp_param_0 = fsdp_params[foreach_copy_indices[0]]
|
| 261 |
+
param_dtype, device = fsdp_param_0.param_dtype, fsdp_param_0.device
|
| 262 |
+
flat_foreach_copy_input = torch.empty(
|
| 263 |
+
(sum(foreach_copy_input_numels),), device=device, dtype=param_dtype
|
| 264 |
+
)
|
| 265 |
+
splits = torch.split(flat_foreach_copy_input, foreach_copy_input_numels)
|
| 266 |
+
torch._foreach_copy_(splits, foreach_copy_inputs)
|
| 267 |
+
for i, split in zip(foreach_copy_indices, splits):
|
| 268 |
+
param_all_gather_inputs[i] = [split]
|
| 269 |
+
|
| 270 |
+
return param_all_gather_inputs
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
@torch.no_grad()
|
| 274 |
+
def foreach_all_gather_copy_out(
|
| 275 |
+
all_gather_result: AllGatherResult,
|
| 276 |
+
fsdp_params: list[FSDPParam],
|
| 277 |
+
group: dist.ProcessGroup,
|
| 278 |
+
) -> None:
|
| 279 |
+
(
|
| 280 |
+
all_gather_output,
|
| 281 |
+
all_gather_event,
|
| 282 |
+
all_gather_work,
|
| 283 |
+
param_all_gather_input_dtypes,
|
| 284 |
+
param_all_gather_input_numels,
|
| 285 |
+
all_gather_input_split_sizes,
|
| 286 |
+
) = all_gather_result
|
| 287 |
+
_dtype, device = all_gather_output.dtype, all_gather_output.device
|
| 288 |
+
device_handle = _get_device_handle(device.type)
|
| 289 |
+
if all_gather_event is not None: # sync op
|
| 290 |
+
device_handle.current_stream().wait_event(all_gather_event)
|
| 291 |
+
if isinstance(all_gather_work, dist.distributed_c10d.Work): # async op
|
| 292 |
+
all_gather_work.wait()
|
| 293 |
+
world_size, device = group.size(), all_gather_output.device
|
| 294 |
+
|
| 295 |
+
split_with_sizes_out: list[torch.Tensor] = []
|
| 296 |
+
shard_i_copy_infos: list[tuple[FSDPParam, list[torch.Tensor]]] = []
|
| 297 |
+
for all_gather_input_numels, all_gather_input_dtypes, fsdp_param in zip(
|
| 298 |
+
param_all_gather_input_numels, param_all_gather_input_dtypes, fsdp_params
|
| 299 |
+
):
|
| 300 |
+
# NOTE: Under compile, make sure we always recreate all_gather_outputs
|
| 301 |
+
# per AllGather. See [Note: Invariants for torch.compile Traceable FSDP2].
|
| 302 |
+
force_recreate = compiled_autograd_enabled()
|
| 303 |
+
fsdp_param.init_all_gather_outputs(
|
| 304 |
+
all_gather_input_numels,
|
| 305 |
+
all_gather_input_dtypes,
|
| 306 |
+
world_size,
|
| 307 |
+
device,
|
| 308 |
+
force_recreate=force_recreate,
|
| 309 |
+
)
|
| 310 |
+
if not force_recreate:
|
| 311 |
+
fsdp_param.alloc_all_gather_outputs()
|
| 312 |
+
param_all_gather_outputs = fsdp_param.all_gather_outputs
|
| 313 |
+
if fsdp_param.fsdp_placement.dim != 0:
|
| 314 |
+
# Copy to a temporary and then chunk-cat into the final all-gather
|
| 315 |
+
# output tensors
|
| 316 |
+
param_all_gather_outputs = [
|
| 317 |
+
torch.empty_like(t) for t in param_all_gather_outputs
|
| 318 |
+
]
|
| 319 |
+
shard_i_copy_infos.append((fsdp_param, param_all_gather_outputs))
|
| 320 |
+
split_with_sizes_out.extend(param_all_gather_outputs)
|
| 321 |
+
|
| 322 |
+
all_gather_output = all_gather_output.view(world_size, -1)
|
| 323 |
+
if all_gather_output.dtype == torch.uint8:
|
| 324 |
+
out = [t.view(world_size, -1).view(torch.uint8) for t in split_with_sizes_out]
|
| 325 |
+
else:
|
| 326 |
+
out = [t.view(world_size, -1) for t in split_with_sizes_out]
|
| 327 |
+
|
| 328 |
+
# only avoid VC bump if we are not in inference mode
|
| 329 |
+
if torch._dynamo.is_compiling():
|
| 330 |
+
# For torch.compile, we turn off inference_mode for fake tensor
|
| 331 |
+
# propagation, and therefore graph break on is_inference. For `compile`,
|
| 332 |
+
# we don't care about VCs, so just skip the optimization.
|
| 333 |
+
non_inference_outs = []
|
| 334 |
+
else:
|
| 335 |
+
non_inference_outs = [o for o in out if not o.is_inference()]
|
| 336 |
+
|
| 337 |
+
if len(non_inference_outs) > 0:
|
| 338 |
+
with torch.autograd._unsafe_preserve_version_counter(tuple(non_inference_outs)):
|
| 339 |
+
torch.ops.fsdp.split_with_sizes_copy(
|
| 340 |
+
all_gather_output, all_gather_input_split_sizes, dim=1, out=out
|
| 341 |
+
)
|
| 342 |
+
else:
|
| 343 |
+
torch.ops.fsdp.split_with_sizes_copy(
|
| 344 |
+
all_gather_output, all_gather_input_split_sizes, dim=1, out=out
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
for fsdp_param, param_all_gather_outputs in shard_i_copy_infos:
|
| 348 |
+
# Chunk-cat from the temporary to the final all-gather output tensors
|
| 349 |
+
shard_dim = fsdp_param.fsdp_placement.dim
|
| 350 |
+
|
| 351 |
+
with torch.autograd._unsafe_preserve_version_counter(
|
| 352 |
+
tuple(fsdp_param.all_gather_outputs)
|
| 353 |
+
):
|
| 354 |
+
for param_all_gather_output, target_all_gather_output in zip(
|
| 355 |
+
param_all_gather_outputs, fsdp_param.all_gather_outputs
|
| 356 |
+
):
|
| 357 |
+
padded_sharded_size = (
|
| 358 |
+
fsdp_param.padded_sharded_param_size
|
| 359 |
+
if fsdp_param.sharded_state == ShardedState.SHARDED
|
| 360 |
+
else cast(
|
| 361 |
+
torch.Tensor, fsdp_param._sharded_post_forward_param_data
|
| 362 |
+
).size()
|
| 363 |
+
)
|
| 364 |
+
pre_param_size = list(padded_sharded_size)
|
| 365 |
+
pre_param_size[0] *= world_size
|
| 366 |
+
chunks = torch.chunk(
|
| 367 |
+
param_all_gather_output.view(pre_param_size), world_size, dim=0
|
| 368 |
+
)
|
| 369 |
+
post_param_size = list(padded_sharded_size)
|
| 370 |
+
post_param_size[shard_dim] *= world_size
|
| 371 |
+
cat_out = target_all_gather_output.view(post_param_size)
|
| 372 |
+
torch.cat(chunks, dim=shard_dim, out=cat_out)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
@torch.no_grad()
|
| 376 |
+
def foreach_reduce(
|
| 377 |
+
fsdp_params: list[FSDPParam],
|
| 378 |
+
unsharded_grads: list[torch.Tensor],
|
| 379 |
+
reduce_scatter_group: dist.ProcessGroup,
|
| 380 |
+
reduce_scatter_stream: torch.Stream,
|
| 381 |
+
orig_dtype: Optional[torch.dtype],
|
| 382 |
+
reduce_dtype: Optional[torch.dtype],
|
| 383 |
+
device: torch.device,
|
| 384 |
+
gradient_divide_factor: Optional[float],
|
| 385 |
+
all_reduce_group: Optional[dist.ProcessGroup], # not `None` iff HSDP
|
| 386 |
+
all_reduce_stream: torch.Stream,
|
| 387 |
+
all_reduce_grads: bool,
|
| 388 |
+
partial_reduce_output: Optional[torch.Tensor], # only used for HSDP
|
| 389 |
+
all_reduce_hook: Optional[Callable[[torch.Tensor], None]],
|
| 390 |
+
allocate_memory_from_process_group: bool = False,
|
| 391 |
+
force_sum_reduction_for_comms: bool = False,
|
| 392 |
+
) -> tuple[
|
| 393 |
+
torch.Tensor,
|
| 394 |
+
torch.Event,
|
| 395 |
+
torch.Event,
|
| 396 |
+
Optional[torch.Tensor],
|
| 397 |
+
Optional[torch.Event],
|
| 398 |
+
Optional[torch.Tensor],
|
| 399 |
+
]:
|
| 400 |
+
"""
|
| 401 |
+
``unsharded_grads`` owns the references to the gradients computed by
|
| 402 |
+
autograd, so clearing the list frees the gradients.
|
| 403 |
+
"""
|
| 404 |
+
grad_dtypes = {grad.dtype for grad in unsharded_grads}
|
| 405 |
+
if len(grad_dtypes) != 1:
|
| 406 |
+
# Check this at runtime since it could be a real runtime error if e.g.
|
| 407 |
+
# fp8 weights do not produce the correct higher precision gradients
|
| 408 |
+
_raise_assert_with_print(
|
| 409 |
+
f"FSDP reduce-scatter expects uniform gradient dtype but got {grad_dtypes}"
|
| 410 |
+
)
|
| 411 |
+
grad_dtype = unsharded_grads[0].dtype
|
| 412 |
+
reduce_dtype = reduce_dtype or grad_dtype
|
| 413 |
+
(predivide_factor, postdivide_factor, reduce_scatter_op, all_reduce_op) = (
|
| 414 |
+
_get_gradient_divide_factors(
|
| 415 |
+
reduce_scatter_group,
|
| 416 |
+
all_reduce_group,
|
| 417 |
+
reduce_dtype,
|
| 418 |
+
device.type,
|
| 419 |
+
gradient_divide_factor,
|
| 420 |
+
force_sum_reduction_for_comms,
|
| 421 |
+
)
|
| 422 |
+
)
|
| 423 |
+
world_size = reduce_scatter_group.size()
|
| 424 |
+
for i, (fsdp_param, unsharded_grad) in enumerate(zip(fsdp_params, unsharded_grads)):
|
| 425 |
+
if (shard_dim := fsdp_param.fsdp_placement.dim) == 0:
|
| 426 |
+
continue
|
| 427 |
+
assert unsharded_grad.size(shard_dim) % world_size == 0, (
|
| 428 |
+
f"Shard({shard_dim}) requires even sharding: {unsharded_grad.size()=} {world_size=}"
|
| 429 |
+
)
|
| 430 |
+
chunks = torch.chunk(unsharded_grad, world_size, dim=shard_dim)
|
| 431 |
+
unsharded_grads[i] = torch.cat(chunks, dim=0)
|
| 432 |
+
padded_unsharded_sizes = tuple(
|
| 433 |
+
_get_dim0_padded_size(grad.size(), world_size) for grad in unsharded_grads
|
| 434 |
+
)
|
| 435 |
+
reduce_scatter_input_numel = sum(s.numel() for s in padded_unsharded_sizes)
|
| 436 |
+
reduce_scatter_output_numel = reduce_scatter_input_numel // world_size
|
| 437 |
+
reduce_scatter_input = allocate_memory(
|
| 438 |
+
reduce_scatter_input_numel,
|
| 439 |
+
dtype=reduce_dtype,
|
| 440 |
+
device=device,
|
| 441 |
+
group=reduce_scatter_group,
|
| 442 |
+
from_process_group=allocate_memory_from_process_group,
|
| 443 |
+
)
|
| 444 |
+
device_handle = _get_device_handle(device.type)
|
| 445 |
+
foreach_reduce_scatter_copy_in(unsharded_grads, reduce_scatter_input, world_size)
|
| 446 |
+
current_stream = device_handle.current_stream()
|
| 447 |
+
# Only after the copy-in finishes can we free the gradients
|
| 448 |
+
unsharded_grads.clear()
|
| 449 |
+
reduce_scatter_stream.wait_stream(current_stream)
|
| 450 |
+
all_reduce_input = None
|
| 451 |
+
all_reduce_event = None
|
| 452 |
+
with device_handle.stream(reduce_scatter_stream):
|
| 453 |
+
reduce_output = allocate_memory(
|
| 454 |
+
reduce_scatter_output_numel,
|
| 455 |
+
dtype=reduce_dtype,
|
| 456 |
+
device=device,
|
| 457 |
+
group=reduce_scatter_group,
|
| 458 |
+
from_process_group=allocate_memory_from_process_group,
|
| 459 |
+
)
|
| 460 |
+
_div_if_needed(reduce_scatter_input, predivide_factor)
|
| 461 |
+
dist.reduce_scatter_tensor(
|
| 462 |
+
output=reduce_output,
|
| 463 |
+
input=reduce_scatter_input,
|
| 464 |
+
group=reduce_scatter_group,
|
| 465 |
+
op=reduce_scatter_op,
|
| 466 |
+
)
|
| 467 |
+
reduce_scatter_event = reduce_scatter_stream.record_event()
|
| 468 |
+
post_reduce_stream = reduce_scatter_stream
|
| 469 |
+
if all_reduce_group is not None: # HSDP
|
| 470 |
+
# Accumulations must run in the reduce-scatter stream
|
| 471 |
+
if not all_reduce_grads:
|
| 472 |
+
if partial_reduce_output is not None:
|
| 473 |
+
partial_reduce_output += reduce_output
|
| 474 |
+
else:
|
| 475 |
+
partial_reduce_output = reduce_output
|
| 476 |
+
return (
|
| 477 |
+
reduce_scatter_input,
|
| 478 |
+
reduce_scatter_event,
|
| 479 |
+
post_reduce_stream.record_event(),
|
| 480 |
+
all_reduce_input,
|
| 481 |
+
all_reduce_event,
|
| 482 |
+
partial_reduce_output,
|
| 483 |
+
)
|
| 484 |
+
if partial_reduce_output is not None:
|
| 485 |
+
reduce_output += partial_reduce_output
|
| 486 |
+
post_reduce_stream = all_reduce_stream
|
| 487 |
+
all_reduce_stream.wait_stream(reduce_scatter_stream)
|
| 488 |
+
with device_handle.stream(all_reduce_stream):
|
| 489 |
+
dist.all_reduce(
|
| 490 |
+
reduce_output,
|
| 491 |
+
group=all_reduce_group,
|
| 492 |
+
op=all_reduce_op,
|
| 493 |
+
)
|
| 494 |
+
all_reduce_input = reduce_output
|
| 495 |
+
all_reduce_event = all_reduce_stream.record_event()
|
| 496 |
+
# -- END: ops in reduce_scatter stream
|
| 497 |
+
|
| 498 |
+
if all_reduce_hook is not None:
|
| 499 |
+
# Execute user-specified all reduce hook.
|
| 500 |
+
# If native HSDP is used, this is executed after the HSDP all reduce.
|
| 501 |
+
# If 1-d FSDP is used, this is executed post reduce-scatter.
|
| 502 |
+
post_reduce_stream = all_reduce_stream
|
| 503 |
+
all_reduce_stream.wait_stream(reduce_scatter_stream)
|
| 504 |
+
with device_handle.stream(all_reduce_stream):
|
| 505 |
+
all_reduce_hook(reduce_output)
|
| 506 |
+
# -- END: ops post reduce_scatter
|
| 507 |
+
|
| 508 |
+
with device_handle.stream(post_reduce_stream):
|
| 509 |
+
_div_if_needed(reduce_output, postdivide_factor)
|
| 510 |
+
reduce_output = _to_dtype_if_needed(reduce_output, orig_dtype)
|
| 511 |
+
# View out and accumulate sharded gradients
|
| 512 |
+
flat_grad_offset = 0 # [0, reduce_scatter_output_numel - 1]
|
| 513 |
+
for padded_unsharded_size, fsdp_param in zip(
|
| 514 |
+
padded_unsharded_sizes, fsdp_params
|
| 515 |
+
):
|
| 516 |
+
# Assume even sharding for Shard(i), i > 0; otherwise would require
|
| 517 |
+
# copy-out for contiguous strides
|
| 518 |
+
new_sharded_grad = torch.as_strided(
|
| 519 |
+
reduce_output,
|
| 520 |
+
size=fsdp_param.sharded_size,
|
| 521 |
+
stride=fsdp_param.contiguous_sharded_stride,
|
| 522 |
+
storage_offset=flat_grad_offset,
|
| 523 |
+
)
|
| 524 |
+
to_accumulate_grad = fsdp_param.sharded_param.grad is not None
|
| 525 |
+
if fsdp_param.offload_to_cpu:
|
| 526 |
+
# Only overlap the D2H copy (copying to pinned memory) if not
|
| 527 |
+
# accumulating gradients since the CPU add kernel depends on
|
| 528 |
+
# the copy result and we cannot run the add as a callback
|
| 529 |
+
non_blocking = fsdp_param.pin_memory and not to_accumulate_grad
|
| 530 |
+
# Since the GPU sharded gradient is allocated in the RS stream,
|
| 531 |
+
# we can free it here by not keeping a ref without waiting for
|
| 532 |
+
# the D2H copy since future RS-stream ops run after the copy
|
| 533 |
+
new_sharded_grad = new_sharded_grad.to(
|
| 534 |
+
torch.device("cpu"), non_blocking=non_blocking
|
| 535 |
+
)
|
| 536 |
+
if non_blocking:
|
| 537 |
+
# Record an event on which to block the CPU thread to
|
| 538 |
+
# ensure that the D2H copy finishes before the optimizer
|
| 539 |
+
fsdp_param.grad_offload_event = reduce_scatter_stream.record_event()
|
| 540 |
+
if to_accumulate_grad:
|
| 541 |
+
assert isinstance(fsdp_param.sharded_param.grad, DTensor)
|
| 542 |
+
fsdp_param.sharded_param.grad._local_tensor += new_sharded_grad
|
| 543 |
+
else:
|
| 544 |
+
new_sharded_dtensor_grad = fsdp_param.to_sharded_dtensor(
|
| 545 |
+
new_sharded_grad
|
| 546 |
+
)
|
| 547 |
+
fsdp_param.sharded_param.grad = new_sharded_dtensor_grad
|
| 548 |
+
if not compiled_autograd_enabled():
|
| 549 |
+
for hook in (
|
| 550 |
+
getattr(fsdp_param.sharded_param, "_post_accumulate_grad_hooks", {})
|
| 551 |
+
or {}
|
| 552 |
+
).values():
|
| 553 |
+
hook(fsdp_param.sharded_param)
|
| 554 |
+
padded_sharded_numel = padded_unsharded_size.numel() // world_size
|
| 555 |
+
flat_grad_offset += padded_sharded_numel
|
| 556 |
+
post_reduce_event = post_reduce_stream.record_event()
|
| 557 |
+
# The RS output is allocated in the RS stream and used in the default
|
| 558 |
+
# stream (for optimizer). To ensure its memory is not reused for later
|
| 559 |
+
# RSs, we do not need extra synchronization since the sharded parameters
|
| 560 |
+
# hold refs through the end of backward.
|
| 561 |
+
return (
|
| 562 |
+
reduce_scatter_input,
|
| 563 |
+
reduce_scatter_event,
|
| 564 |
+
post_reduce_event,
|
| 565 |
+
all_reduce_input,
|
| 566 |
+
all_reduce_event,
|
| 567 |
+
None,
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def foreach_reduce_scatter_copy_in(
|
| 572 |
+
unsharded_grads: list[torch.Tensor],
|
| 573 |
+
reduce_scatter_input: torch.Tensor,
|
| 574 |
+
world_size: int,
|
| 575 |
+
) -> None:
|
| 576 |
+
reduce_scatter_input = reduce_scatter_input.view(world_size, -1)
|
| 577 |
+
torch.ops.fsdp.chunk_cat(
|
| 578 |
+
unsharded_grads, dim=0, num_chunks=world_size, out=reduce_scatter_input
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def _get_all_gather_input_metadatas(
|
| 583 |
+
param_all_gather_inputs: list[list[torch.Tensor]],
|
| 584 |
+
) -> tuple[list[list[torch.dtype]], list[list[int]], torch.dtype]:
|
| 585 |
+
param_all_gather_input_dtypes: list[list[torch.dtype]] = []
|
| 586 |
+
param_all_gather_input_numels: list[list[int]] = []
|
| 587 |
+
all_gather_dtype = param_all_gather_inputs[0][0].dtype
|
| 588 |
+
for all_gather_inputs in param_all_gather_inputs:
|
| 589 |
+
input_dtypes: list[torch.dtype] = []
|
| 590 |
+
input_numels: list[int] = []
|
| 591 |
+
for all_gather_input in all_gather_inputs:
|
| 592 |
+
if all_gather_input.dtype != all_gather_dtype:
|
| 593 |
+
all_gather_dtype = torch.uint8
|
| 594 |
+
input_dtypes.append(all_gather_input.dtype)
|
| 595 |
+
input_numels.append(all_gather_input.numel())
|
| 596 |
+
param_all_gather_input_dtypes.append(input_dtypes)
|
| 597 |
+
param_all_gather_input_numels.append(input_numels)
|
| 598 |
+
return (
|
| 599 |
+
param_all_gather_input_dtypes,
|
| 600 |
+
param_all_gather_input_numels,
|
| 601 |
+
all_gather_dtype,
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def _get_gradient_divide_factors(
|
| 606 |
+
reduce_scatter_group: dist.ProcessGroup,
|
| 607 |
+
all_reduce_group: Optional[dist.ProcessGroup],
|
| 608 |
+
reduce_dtype: torch.dtype,
|
| 609 |
+
device_type: str = "",
|
| 610 |
+
factor: Optional[float] = None,
|
| 611 |
+
force_sum_reduction_for_comms: bool = False,
|
| 612 |
+
) -> tuple[
|
| 613 |
+
Optional[float],
|
| 614 |
+
Optional[float],
|
| 615 |
+
Union[dist.ReduceOp, dist.ReduceOp.RedOpType],
|
| 616 |
+
Union[dist.ReduceOp, dist.ReduceOp.RedOpType],
|
| 617 |
+
]:
|
| 618 |
+
# MTIA appears to only support SUM reduction, hence we force it implicitly
|
| 619 |
+
if device_type == "mtia":
|
| 620 |
+
force_sum_reduction_for_comms = True
|
| 621 |
+
|
| 622 |
+
# For fp32/bf16, we do not need to worry about overflow/underflow, so we
|
| 623 |
+
# use NCCL's built-in division to avoid separate div kernels
|
| 624 |
+
overflow_risk = reduce_dtype not in (torch.float32, torch.bfloat16)
|
| 625 |
+
|
| 626 |
+
data_parallel_size = reduce_scatter_group.size()
|
| 627 |
+
if all_reduce_group is not None:
|
| 628 |
+
data_parallel_size *= all_reduce_group.size()
|
| 629 |
+
|
| 630 |
+
if factor is None:
|
| 631 |
+
factor = float(data_parallel_size)
|
| 632 |
+
|
| 633 |
+
if not overflow_risk and not force_sum_reduction_for_comms:
|
| 634 |
+
if factor == data_parallel_size:
|
| 635 |
+
# Warning: NCCL ReduceOp.AVG may produce incorrect results with
|
| 636 |
+
# world size 1.
|
| 637 |
+
return None, None, ReduceOp.AVG, ReduceOp.AVG
|
| 638 |
+
else:
|
| 639 |
+
reduce_scatter_op = torch.distributed._make_nccl_premul_sum(1 / factor)
|
| 640 |
+
return None, None, reduce_scatter_op, ReduceOp.SUM
|
| 641 |
+
|
| 642 |
+
pre_factor: Optional[float]
|
| 643 |
+
if overflow_risk:
|
| 644 |
+
# Since fp16 has smaller dynamic range than fp32/bf16, we want to avoid
|
| 645 |
+
# overflow/underflow. For N data parallel workers, each worker computes
|
| 646 |
+
# g_i, and they collectively reduce (g_1 + ... + g_N) / N. To avoid
|
| 647 |
+
# overflow/underflow, we divide by ~sqrt(N) before/after the reduction.
|
| 648 |
+
pre_factor = 1
|
| 649 |
+
while factor % pre_factor == 0 and factor / pre_factor > pre_factor:
|
| 650 |
+
pre_factor *= 2
|
| 651 |
+
post_factor = factor / pre_factor
|
| 652 |
+
else:
|
| 653 |
+
# Prefer post-multiplying as it operates on less data and is thus faster
|
| 654 |
+
pre_factor, post_factor = None, factor
|
| 655 |
+
|
| 656 |
+
return pre_factor, post_factor, ReduceOp.SUM, ReduceOp.SUM
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def _div_if_needed(tensor: torch.Tensor, div_factor: Optional[float]) -> None:
|
| 660 |
+
if div_factor is not None and div_factor != 1:
|
| 661 |
+
tensor.div_(div_factor)
|
_fsdp_common.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import math
|
| 3 |
+
import traceback
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from enum import auto, Enum
|
| 6 |
+
from typing import Any, Optional
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.distributed as dist
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from torch.distributed._composable.contract import _get_registry
|
| 12 |
+
from torch.distributed.tensor import DeviceMesh, DTensor
|
| 13 |
+
from torch.distributed.tensor._dtensor_spec import DTensorSpec
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
_compiled_autograd_enabled: bool = False
|
| 17 |
+
|
| 18 |
+
if torch._running_with_deploy():
|
| 19 |
+
|
| 20 |
+
def detect_compiled_autograd():
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
def compiled_autograd_enabled():
|
| 24 |
+
return False
|
| 25 |
+
|
| 26 |
+
else:
|
| 27 |
+
|
| 28 |
+
def detect_compiled_autograd():
|
| 29 |
+
assert not torch.compiler.is_compiling(), (
|
| 30 |
+
"`detect_compiled_autograd()` is designed to be called in eager mode"
|
| 31 |
+
)
|
| 32 |
+
global _compiled_autograd_enabled
|
| 33 |
+
import torch._dynamo.compiled_autograd as ca
|
| 34 |
+
|
| 35 |
+
_compiled_autograd_enabled = (
|
| 36 |
+
ca.compiled_autograd_enabled
|
| 37 |
+
or ca.compiled_autograd_enabled_force_eager
|
| 38 |
+
or ca.in_compiled_autograd_region
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def compiled_autograd_enabled():
|
| 42 |
+
global _compiled_autograd_enabled
|
| 43 |
+
return _compiled_autograd_enabled
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclass
|
| 47 |
+
class DataParallelMeshInfo:
|
| 48 |
+
mesh: DeviceMesh
|
| 49 |
+
shard_mesh_dim: Optional[int] = None
|
| 50 |
+
replicate_mesh_dim: Optional[int] = None
|
| 51 |
+
|
| 52 |
+
def __post_init__(self):
|
| 53 |
+
if self.shard_mesh_dim is None and self.replicate_mesh_dim is None:
|
| 54 |
+
raise AssertionError(
|
| 55 |
+
"At least one of shard_mesh_dim and replicate_mesh_dim must not be None"
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@dataclass
|
| 60 |
+
class FSDPMeshInfo(DataParallelMeshInfo):
|
| 61 |
+
def __post_init__(self):
|
| 62 |
+
super().__post_init__()
|
| 63 |
+
if self.shard_mesh_dim is None:
|
| 64 |
+
raise AssertionError("Expects non-None shard_mesh_dim")
|
| 65 |
+
self.shard_mesh_size: int = self.mesh.size(self.shard_mesh_dim)
|
| 66 |
+
self.shard_process_group = self.mesh.get_group(self.shard_mesh_dim)
|
| 67 |
+
self.shard_mesh_rank: int = self.shard_process_group.rank()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass
|
| 71 |
+
class DDPMeshInfo(DataParallelMeshInfo):
|
| 72 |
+
def __post_init__(self):
|
| 73 |
+
super().__post_init__()
|
| 74 |
+
if self.replicate_mesh_dim is None:
|
| 75 |
+
raise AssertionError("Expects non-None replicate_mesh_dim")
|
| 76 |
+
self.replicate_mesh_size: int = self.mesh.size(self.replicate_mesh_dim)
|
| 77 |
+
self.replicate_process_group = self.mesh.get_group(self.replicate_mesh_dim)
|
| 78 |
+
self.replicate_mesh_rank: int = self.replicate_process_group.rank()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@dataclass
|
| 82 |
+
class HSDPMeshInfo(FSDPMeshInfo, DDPMeshInfo):
|
| 83 |
+
def __post_init__(self):
|
| 84 |
+
# Calls `FSDPMeshInfo` -> `DDPMeshInfo` -> `DataParallelMeshInfo`
|
| 85 |
+
super().__post_init__()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class TrainingState(Enum):
|
| 89 |
+
"""Describes the training state of one FSDP state / parameter group."""
|
| 90 |
+
|
| 91 |
+
# Transition to forward starting pre-forward until post-forward
|
| 92 |
+
FORWARD = auto()
|
| 93 |
+
# Transition to pre-backward when unsharding in backward
|
| 94 |
+
PRE_BACKWARD = auto()
|
| 95 |
+
# Transition to post-backward when resharding and reducing gradients
|
| 96 |
+
POST_BACKWARD = auto()
|
| 97 |
+
# Idle before/after forward or before pre-backward/after post-backward
|
| 98 |
+
IDLE = auto()
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _raise_assert_with_print(*args: Any, **kwargs: Any):
|
| 102 |
+
print(f"[Rank {dist.get_rank()}] ", end="")
|
| 103 |
+
print(*args, **kwargs)
|
| 104 |
+
traceback.print_stack()
|
| 105 |
+
raise AssertionError(*args, **kwargs)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _is_composable_with_fsdp(module: nn.Module) -> bool:
|
| 109 |
+
registry = _get_registry(module)
|
| 110 |
+
if registry is None:
|
| 111 |
+
return True
|
| 112 |
+
# Registry keys by function name
|
| 113 |
+
return "replicate" not in registry
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _get_dim0_padded_size(tensor_size: torch.Size, dim0_factor: int) -> torch.Size:
|
| 117 |
+
padded_dim0 = math.ceil(tensor_size[0] / dim0_factor) * dim0_factor
|
| 118 |
+
return torch.Size([padded_dim0]) + tensor_size[1:]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _chunk_with_empty(
|
| 122 |
+
tensor: torch.Tensor, num_chunks: int, dim: int
|
| 123 |
+
) -> list[torch.Tensor]:
|
| 124 |
+
chunks = list(torch.chunk(tensor, num_chunks, dim=dim))
|
| 125 |
+
while len(chunks) < num_chunks:
|
| 126 |
+
chunks.append(chunks[0].new_empty(0))
|
| 127 |
+
return chunks
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _get_dim_chunked_size(
|
| 131 |
+
chunk: torch.Tensor, unchunked_size: torch.Size, dim: int
|
| 132 |
+
) -> torch.Size:
|
| 133 |
+
if chunk.numel() > 0:
|
| 134 |
+
return chunk.size()
|
| 135 |
+
# For 0 numel, we need to preserve nonzero-sized dims for DTensor APIs
|
| 136 |
+
return unchunked_size[:dim] + torch.Size([0]) + unchunked_size[dim + 1 :]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _from_local_no_grad(
|
| 140 |
+
local_tensor: torch.Tensor,
|
| 141 |
+
sharding_spec: DTensorSpec,
|
| 142 |
+
) -> DTensor:
|
| 143 |
+
"""
|
| 144 |
+
This method is similar to ``DTensor.from_local()`` except that in eager mode
|
| 145 |
+
it avoids some CPU overhead by avoiding default args and not being differentiable.
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
if not compiled_autograd_enabled():
|
| 149 |
+
return DTensor(
|
| 150 |
+
# Use the local tensor directly instead of constructing a new tensor
|
| 151 |
+
# variable, e.g. with `view_as()`, since this is not differentiable
|
| 152 |
+
local_tensor,
|
| 153 |
+
sharding_spec,
|
| 154 |
+
requires_grad=local_tensor.requires_grad,
|
| 155 |
+
)
|
| 156 |
+
else:
|
| 157 |
+
return DTensor.from_local(
|
| 158 |
+
local_tensor,
|
| 159 |
+
sharding_spec.mesh,
|
| 160 |
+
sharding_spec.placements,
|
| 161 |
+
shape=sharding_spec.shape,
|
| 162 |
+
stride=sharding_spec.stride,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _to_dtype_if_needed(
|
| 167 |
+
tensor: torch.Tensor, dtype: Optional[torch.dtype]
|
| 168 |
+
) -> torch.Tensor:
|
| 169 |
+
if dtype is not None and tensor.dtype != dtype:
|
| 170 |
+
return tensor.to(dtype)
|
| 171 |
+
return tensor
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _cast_fp_tensor(dtype: torch.dtype, x: torch.Tensor) -> torch.Tensor:
|
| 175 |
+
if (
|
| 176 |
+
not isinstance(x, torch.Tensor)
|
| 177 |
+
or not torch.is_floating_point(x)
|
| 178 |
+
or x.dtype == dtype
|
| 179 |
+
):
|
| 180 |
+
return x
|
| 181 |
+
return x.to(dtype)
|
_fsdp_init.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import logging
|
| 3 |
+
from typing import Optional, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.distributed as dist
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
from torch._logging import warning_once
|
| 9 |
+
from torch.distributed.device_mesh import _get_device_handle
|
| 10 |
+
from torch.distributed.tensor import DeviceMesh, DTensor, init_device_mesh
|
| 11 |
+
from torch.utils._python_dispatch import is_traceable_wrapper_subclass
|
| 12 |
+
|
| 13 |
+
from ._fsdp_common import _is_composable_with_fsdp, FSDPMeshInfo, HSDPMeshInfo
|
| 14 |
+
from ._fsdp_state import _get_module_fsdp_state
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger("torch.distributed.fsdp.fully_shard")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _get_post_forward_mesh_info(
|
| 21 |
+
reshard_after_forward: Union[bool, int], mesh_info: FSDPMeshInfo
|
| 22 |
+
) -> Optional[FSDPMeshInfo]:
|
| 23 |
+
shard_mesh_size = mesh_info.shard_mesh_size
|
| 24 |
+
if not isinstance(reshard_after_forward, (bool, int)):
|
| 25 |
+
raise ValueError(
|
| 26 |
+
"reshard_after_forward should be a bool or an int representing the "
|
| 27 |
+
f"group size to reshard to, not {reshard_after_forward}"
|
| 28 |
+
)
|
| 29 |
+
# NOTE: `isinstance(False, int)` returns `True`.
|
| 30 |
+
if not isinstance(reshard_after_forward, bool) and isinstance(
|
| 31 |
+
reshard_after_forward, int
|
| 32 |
+
):
|
| 33 |
+
if (
|
| 34 |
+
reshard_after_forward < 1
|
| 35 |
+
or reshard_after_forward > shard_mesh_size
|
| 36 |
+
or shard_mesh_size % reshard_after_forward != 0
|
| 37 |
+
):
|
| 38 |
+
raise ValueError(
|
| 39 |
+
"If passing reshard_after_forward as an int, it should be a "
|
| 40 |
+
f"factor of {shard_mesh_size}, not {reshard_after_forward}"
|
| 41 |
+
)
|
| 42 |
+
elif reshard_after_forward == 1:
|
| 43 |
+
msg = (
|
| 44 |
+
"reshard_after_forward=1 (int) means resharding parameters to world size 1, "
|
| 45 |
+
"instead of reshard_after_forward=True (bool)"
|
| 46 |
+
)
|
| 47 |
+
warning_once(logger, msg, stacklevel=2)
|
| 48 |
+
reshard_after_forward = False
|
| 49 |
+
elif reshard_after_forward == shard_mesh_size:
|
| 50 |
+
reshard_after_forward = True
|
| 51 |
+
post_forward_mesh_info = None
|
| 52 |
+
if reshard_after_forward is True:
|
| 53 |
+
post_forward_mesh_info = mesh_info
|
| 54 |
+
elif reshard_after_forward is not False: # int case
|
| 55 |
+
# For HSDP, we can flatten the two replicate dims into the 0th dim
|
| 56 |
+
post_forward_mesh_tensor = mesh_info.mesh.mesh.view(-1, reshard_after_forward)
|
| 57 |
+
post_forward_mesh = DeviceMesh(
|
| 58 |
+
mesh_info.mesh.device_type, post_forward_mesh_tensor
|
| 59 |
+
)
|
| 60 |
+
post_forward_mesh_info = HSDPMeshInfo(
|
| 61 |
+
post_forward_mesh, shard_mesh_dim=1, replicate_mesh_dim=0
|
| 62 |
+
)
|
| 63 |
+
return post_forward_mesh_info
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _init_default_fully_shard_mesh() -> DeviceMesh:
|
| 67 |
+
"""Default to global CUDA mesh if possible else global CPU mesh."""
|
| 68 |
+
if not dist.distributed_c10d.is_initialized():
|
| 69 |
+
dist.distributed_c10d.init_process_group()
|
| 70 |
+
default_pg = dist.distributed_c10d._get_default_group()
|
| 71 |
+
device = torch._C._get_accelerator()
|
| 72 |
+
mesh = init_device_mesh(device.type, mesh_shape=(default_pg.size(),))
|
| 73 |
+
return mesh
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _get_device_from_mesh(mesh: DeviceMesh) -> torch.device:
|
| 77 |
+
if mesh.device_type == "cpu":
|
| 78 |
+
return torch.device("cpu")
|
| 79 |
+
device_handle = _get_device_handle(mesh.device_type)
|
| 80 |
+
return torch.device(mesh.device_type, device_handle.current_device())
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _ignore_module(
|
| 84 |
+
module: nn.Module,
|
| 85 |
+
ignored_params: set[nn.Parameter],
|
| 86 |
+
ignore_decision: dict[nn.Module, bool],
|
| 87 |
+
) -> bool:
|
| 88 |
+
"""
|
| 89 |
+
Decide if it is safe to ignore a module for applying fully_shard.
|
| 90 |
+
"""
|
| 91 |
+
if module in ignore_decision:
|
| 92 |
+
return ignore_decision[module]
|
| 93 |
+
|
| 94 |
+
if len(list(module.buffers(recurse=False))) > 0:
|
| 95 |
+
# Cannot ignore a module with any buffer
|
| 96 |
+
ignore_decision[module] = False
|
| 97 |
+
return False
|
| 98 |
+
|
| 99 |
+
for _, param in module.named_parameters(recurse=False):
|
| 100 |
+
if param not in ignored_params:
|
| 101 |
+
# at least one param is not ignored. So this module shouldn't be.
|
| 102 |
+
ignore_decision[module] = False
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
# Need to consider descendants of module
|
| 106 |
+
for child in list(module.children()):
|
| 107 |
+
ignore_child = _ignore_module(child, ignored_params, ignore_decision)
|
| 108 |
+
if not ignore_child:
|
| 109 |
+
# Cannot ignore module if one of its children is not ignored
|
| 110 |
+
ignore_decision[module] = False
|
| 111 |
+
return False
|
| 112 |
+
|
| 113 |
+
# Safe to ignore module
|
| 114 |
+
ignore_decision[module] = True
|
| 115 |
+
return True
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _adjust_managed_modules(
|
| 119 |
+
modules: list[nn.Module], ignored_params: set[nn.Parameter]
|
| 120 |
+
) -> list[nn.Module]:
|
| 121 |
+
"""
|
| 122 |
+
Adjust the given list of managed modules by removing those with all parameters ignored.
|
| 123 |
+
"""
|
| 124 |
+
ignore_decision: dict[nn.Module, bool] = {}
|
| 125 |
+
new_modules = []
|
| 126 |
+
for module in modules:
|
| 127 |
+
ignored = _ignore_module(module, ignored_params, ignore_decision)
|
| 128 |
+
if not ignored:
|
| 129 |
+
new_modules.append(module)
|
| 130 |
+
return new_modules
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _get_managed_modules(
|
| 134 |
+
root_modules: tuple[nn.Module, ...],
|
| 135 |
+
ignored_params: Optional[set[nn.Parameter]] = None,
|
| 136 |
+
) -> list[nn.Module]:
|
| 137 |
+
modules: list[nn.Module] = []
|
| 138 |
+
root_modules_set = set(root_modules)
|
| 139 |
+
# Track visisted modules to avoid visiting shared modules multiple times
|
| 140 |
+
visited_modules: set[nn.Module] = set()
|
| 141 |
+
|
| 142 |
+
def dfs(module: nn.Module) -> None:
|
| 143 |
+
"""
|
| 144 |
+
Runs a DFS to collect managed modules, not recursing into modules with
|
| 145 |
+
a non-composable API or ``fully_shard`` already applied.
|
| 146 |
+
"""
|
| 147 |
+
if not _is_composable_with_fsdp(module):
|
| 148 |
+
return
|
| 149 |
+
elif (
|
| 150 |
+
module not in root_modules_set
|
| 151 |
+
and _get_module_fsdp_state(module) is not None
|
| 152 |
+
):
|
| 153 |
+
return # nested `fully_shard` module
|
| 154 |
+
visited_modules.add(module)
|
| 155 |
+
for submodule in module.children():
|
| 156 |
+
if submodule not in visited_modules:
|
| 157 |
+
dfs(submodule)
|
| 158 |
+
modules.append(module)
|
| 159 |
+
|
| 160 |
+
for root_module in root_modules:
|
| 161 |
+
dfs(root_module)
|
| 162 |
+
|
| 163 |
+
if ignored_params is None:
|
| 164 |
+
return modules
|
| 165 |
+
|
| 166 |
+
adjusted_modules = _adjust_managed_modules(modules, ignored_params)
|
| 167 |
+
return adjusted_modules
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _verify_managed_param(name: str, param: nn.Parameter) -> None:
|
| 171 |
+
"""
|
| 172 |
+
Verify if the parameter is accepted by fully_shard. The only restriction now
|
| 173 |
+
is that the parameter cannot be a scalar tensor (param.numel == 0) since we
|
| 174 |
+
need at least one dim to shard.
|
| 175 |
+
"""
|
| 176 |
+
if len(param.shape) == 0:
|
| 177 |
+
raise ValueError(
|
| 178 |
+
"fully_shard doesn't support scalar parameters. "
|
| 179 |
+
f"Change {name} to a 1D tensor with numel equal to 1."
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _get_managed_states(
|
| 184 |
+
modules: list[nn.Module], ignored_params: Optional[set[nn.Parameter]] = None
|
| 185 |
+
) -> tuple[list[nn.Parameter], list[torch.Tensor]]:
|
| 186 |
+
params: list[nn.Parameter] = []
|
| 187 |
+
buffers: list[torch.Tensor] = []
|
| 188 |
+
# Track visited parameters/buffers to avoid visiting shared parameters and
|
| 189 |
+
# buffers multiple times
|
| 190 |
+
visited_params: set[nn.Parameter] = set()
|
| 191 |
+
visited_buffers: set[torch.Tensor] = set()
|
| 192 |
+
if ignored_params is None:
|
| 193 |
+
ignored_params = set()
|
| 194 |
+
|
| 195 |
+
for module in modules:
|
| 196 |
+
for name, param in module.named_parameters(recurse=False):
|
| 197 |
+
if param in ignored_params:
|
| 198 |
+
# do not include an ignored parameters
|
| 199 |
+
continue
|
| 200 |
+
if param not in visited_params:
|
| 201 |
+
_verify_managed_param(name, param)
|
| 202 |
+
params.append(param)
|
| 203 |
+
visited_params.add(param)
|
| 204 |
+
for buffer in module.buffers(recurse=False):
|
| 205 |
+
if buffer not in visited_buffers:
|
| 206 |
+
buffers.append(buffer)
|
| 207 |
+
visited_buffers.add(buffer)
|
| 208 |
+
return params, buffers
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _move_states_to_device(
|
| 212 |
+
params: list[nn.Parameter],
|
| 213 |
+
buffers: list[torch.Tensor],
|
| 214 |
+
device: torch.device,
|
| 215 |
+
) -> None:
|
| 216 |
+
"""
|
| 217 |
+
We have FSDP move states to device for simpler and faster initialization
|
| 218 |
+
since FSDP almost always uses CUDA for training. We move parameters/buffers
|
| 219 |
+
rather than modules since modules to support ignoring parameters/buffers in
|
| 220 |
+
the future.
|
| 221 |
+
"""
|
| 222 |
+
# Follow the logic in `nn.Module._apply`
|
| 223 |
+
for tensor in itertools.chain(params, buffers):
|
| 224 |
+
if tensor.device == device or tensor.device.type == "meta":
|
| 225 |
+
# Keep meta-device tensors on meta device for deferred init
|
| 226 |
+
continue
|
| 227 |
+
if isinstance(tensor, DTensor):
|
| 228 |
+
if (dtensor_mesh_type := tensor.device_mesh.device_type) != device.type:
|
| 229 |
+
raise ValueError(
|
| 230 |
+
"Requires DTensor to have mesh of the same type as the FSDP mesh "
|
| 231 |
+
f"but got {dtensor_mesh_type} for DTensor and {device.type} for FSDP"
|
| 232 |
+
)
|
| 233 |
+
raise AssertionError(
|
| 234 |
+
f"Expects DTensor to be moved to {dtensor_mesh_type} but got {tensor.device}"
|
| 235 |
+
)
|
| 236 |
+
tensor_ = tensor
|
| 237 |
+
if is_traceable_wrapper_subclass(tensor_):
|
| 238 |
+
with torch.no_grad(): # avoid autograd increasing C++ refcount by 1
|
| 239 |
+
tensor_on_device = nn.Parameter(tensor.to(device))
|
| 240 |
+
torch.utils.swap_tensors(tensor, tensor_on_device)
|
| 241 |
+
else:
|
| 242 |
+
tensor.data = tensor.to(device)
|
_fsdp_param.py
ADDED
|
@@ -0,0 +1,896 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import inspect
|
| 3 |
+
import itertools
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
from dataclasses import dataclass, field
|
| 6 |
+
from enum import auto, Enum
|
| 7 |
+
from typing import Any, Callable, cast, Optional
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from torch._prims_common import make_contiguous_strides_for
|
| 12 |
+
from torch.distributed._functional_collectives import AsyncCollectiveTensor
|
| 13 |
+
from torch.distributed.tensor import DTensor, Replicate, Shard
|
| 14 |
+
from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
|
| 15 |
+
from torch.distributed.tensor.device_mesh import _mesh_resources
|
| 16 |
+
from torch.distributed.tensor.placement_types import _StridedShard, Placement
|
| 17 |
+
|
| 18 |
+
from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
|
| 19 |
+
from ._fsdp_common import (
|
| 20 |
+
_chunk_with_empty,
|
| 21 |
+
_from_local_no_grad,
|
| 22 |
+
_get_dim_chunked_size,
|
| 23 |
+
_raise_assert_with_print,
|
| 24 |
+
_to_dtype_if_needed,
|
| 25 |
+
compiled_autograd_enabled,
|
| 26 |
+
FSDPMeshInfo,
|
| 27 |
+
HSDPMeshInfo,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
"""
|
| 32 |
+
[Note: FSDP tensors]
|
| 33 |
+
FSDP considers the following tensors:
|
| 34 |
+
- Original parameter: parameter passed to :class:`FSDPParam`, i.e. the one
|
| 35 |
+
on the module when applying FSDP
|
| 36 |
+
- Sharded parameter: sharding the original parameter on dim-0 (or a
|
| 37 |
+
user-specified dim) as a DTensor over the main mesh
|
| 38 |
+
- All-gather inputs: the ``torch.Tensor`` or ``Tensor`` s passed to all-gather,
|
| 39 |
+
derived from the sharded parameter
|
| 40 |
+
- All-gather output: the ``torch.Tensor`` or ``Tensor`` s resulting from
|
| 41 |
+
all-gathering the all-gather inputs
|
| 42 |
+
- Unsharded parameter: parameter used for forward/backward computation, derived
|
| 43 |
+
from the all-gather output; autograd leaf
|
| 44 |
+
|
| 45 |
+
We define these tensors to describe the general framework that can accommodate
|
| 46 |
+
extensions, where:
|
| 47 |
+
- all-gather-inputs = pre-all-gather-transform(sharded-parameter)
|
| 48 |
+
- unsharded-parameter = post-all-gather-transform(all-gather-outputs)
|
| 49 |
+
|
| 50 |
+
For the default ``torch.Tensor`` case, there is only one all-gather input, and
|
| 51 |
+
it shares the same underlying tensor data as the sharded parameter, meaning
|
| 52 |
+
that they can be thought of as the same tensors. The same applies for the
|
| 53 |
+
all-gather output and unsharded parameter. For non-``torch.Tensor`` extensions,
|
| 54 |
+
these equivalences may no longer hold due to the pre/post-all-gather
|
| 55 |
+
transforms, and some may have multiple all-gather inputs/outputs (e.g.
|
| 56 |
+
quantized data and scales).
|
| 57 |
+
|
| 58 |
+
[Note: FSDP and autograd]
|
| 59 |
+
FSDP dynamically frees and allocates the unsharded parameter. Since autograd
|
| 60 |
+
can pack a reference to it or a view to save for backward, we use storage
|
| 61 |
+
resizing to implement the freeing/allocation since that preserves the aliasing.
|
| 62 |
+
This implies that we construct the unsharded parameter object once and write to
|
| 63 |
+
it in-place thereafter. For the default ``torch.Tensor` original parameter
|
| 64 |
+
case, the all-gather output and unsharded parameter share the same
|
| 65 |
+
data, so we use storage resizing on the all-gather output.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
lib = torch.library.Library("fsdp", "FRAGMENT") # noqa: TOR901
|
| 69 |
+
|
| 70 |
+
lib.define("copy_(Tensor(a!) tensor, Tensor data) -> ()")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@torch.library.impl(lib, "copy_", "Meta")
|
| 74 |
+
@torch.library.impl(lib, "copy_", "CUDA")
|
| 75 |
+
@torch.library.impl(lib, "copy_", "XPU")
|
| 76 |
+
@torch.library.impl(lib, "copy_", "HPU")
|
| 77 |
+
@torch.library.impl(lib, "copy_", "CPU")
|
| 78 |
+
@torch.library.impl(lib, "copy_", "MTIA")
|
| 79 |
+
def copy_(tensor, data):
|
| 80 |
+
tensor.copy_(data)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
"""
|
| 84 |
+
[Note: Avoiding functionalization for fsdp.copy_ and inductor.resize_storage_bytes_]
|
| 85 |
+
|
| 86 |
+
Currently we don't functionalize `fsdp.copy_` op or `inductor.resize_storage_bytes_` op
|
| 87 |
+
(i.e. they show up as a mutation op in the middle of the AOT joint graph).
|
| 88 |
+
|
| 89 |
+
Reason:
|
| 90 |
+
Traceable FSDP2 compiled autograd BWD graph have the following traits:
|
| 91 |
+
(1) Two inputs of the graph were aliased to each other (one from hook closed-over tensors, one from FWD saved tensors).
|
| 92 |
+
(2) One of them is mutated (copy_ and resize_ to handle the all-gathered param).
|
| 93 |
+
(3) They are both subclasses.
|
| 94 |
+
The combination of these traits is not supported by AOTAutograd (it's difficult to reason about subclass aliasing).
|
| 95 |
+
So this doesn't work at all for Traceable FSDP2.
|
| 96 |
+
|
| 97 |
+
The compromise we use is to avoid functionalization for the FSDP2 copy_ and resize_ ops.
|
| 98 |
+
This avoids the problem above, because from AOTAutograd point-of-view there are no mutations
|
| 99 |
+
that functionalization needs to handle. (Although we need to be careful not to DCE those mutable ops.)
|
| 100 |
+
|
| 101 |
+
We can avoid this functionalization because:
|
| 102 |
+
(1) The nn.Parameter is never used before its .copy_() is called in eager code (i.e. no alias of it is created),
|
| 103 |
+
so it's safe to call .copy_() in the middle of the graph to update its content and start using the nn.Parameter downstream.
|
| 104 |
+
(2) We always re-allocate the buffer for nn.Parameter to store the AllGather output and to be used in downstream user ops.
|
| 105 |
+
So calling resize-to-0 in the middle of the graph to free nn.Parameter memory after use should always be okay
|
| 106 |
+
(since we always allocate anew next time we need it, we strictly don't need to keep the old tensor storage around anymore).
|
| 107 |
+
|
| 108 |
+
Q: Wouldn't the extra resize_ and copy_ ops hurt both memory usage and performance?
|
| 109 |
+
A: Yes it would. As an optimization, we have an Inductor post-grad FX pass to remove those resize_ and copy_ ops
|
| 110 |
+
for unsharded params that have this pattern: resize_(full) -> copy_ -> resize_(0).
|
| 111 |
+
|
| 112 |
+
TODO:
|
| 113 |
+
Now that we are maintaining the invariant of "no aliased + mutated graph inputs" in both the forward and backward,
|
| 114 |
+
it is now more feasible to functionalize all of the mutable FSDP ops. Some of the pros and cons are:
|
| 115 |
+
|
| 116 |
+
Cons (of functionalizing those ops):
|
| 117 |
+
(1) By not functionalizing them as we are today, we are making it more likely that they will run at the "correct" time
|
| 118 |
+
in the generated code. If we start to functionalize them, we will need to make sure that Inductor reinplaces them
|
| 119 |
+
in a way where it properly moves the mutations back to exactly where they should have run, or we risk suffering worse
|
| 120 |
+
peak memory than eager. (We probably already need to do something similar in Inductor's reinplacing for copy_:
|
| 121 |
+
https://github.com/pytorch/pytorch/issues/135305#issuecomment-2334888089)
|
| 122 |
+
|
| 123 |
+
Pros (of functionalizing):
|
| 124 |
+
(1) Better safety, we don't need to worry about the graph passes in inductor/partitioning handling input mutations
|
| 125 |
+
mid-graph quite as much (to be fair we've already done some amount of auditing, but we might have to do some more).
|
| 126 |
+
(2) Better perf: each mutation midway through the graph prevents Inductor from pattern matching across it.
|
| 127 |
+
But maybe there are few enough mutations induced by FSDP for this to matter.
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@torch.library.impl(lib, "copy_", "Functionalize")
|
| 132 |
+
def copy__functionalize(tensor, data):
|
| 133 |
+
torch._sync(tensor)
|
| 134 |
+
torch._sync(data)
|
| 135 |
+
tensor_inner = torch._from_functional_tensor(tensor)
|
| 136 |
+
data_inner = torch._from_functional_tensor(data)
|
| 137 |
+
with torch._C._ExcludeDispatchKeyGuard(
|
| 138 |
+
torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
|
| 139 |
+
):
|
| 140 |
+
torch.ops.fsdp.copy_.default(tensor_inner, data_inner)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
if not torch._running_with_deploy():
|
| 144 |
+
torch.fx.node.has_side_effect(torch.ops.fsdp.copy_.default)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class ShardedState(Enum):
|
| 148 |
+
"""
|
| 149 |
+
- ``SHARDED``: The sharded parameter is registered to the module. It is the
|
| 150 |
+
only contributor to parameter memory.
|
| 151 |
+
- ``SHARDED_POST_FORWARD``: The unsharded parameter is resharded to a
|
| 152 |
+
smaller world size. Since this data should not be used for computation,
|
| 153 |
+
we do not register it to the module. Users should reshard the module
|
| 154 |
+
before any in-place modifications. Both it and the sharded parameter
|
| 155 |
+
contribute to parameter memory.
|
| 156 |
+
- ``UNSHARDED``: The unsharded parameter is registered to the module. Both
|
| 157 |
+
it and the sharded parameter contribute to parameter memory.
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
SHARDED = auto()
|
| 161 |
+
SHARDED_POST_FORWARD = auto()
|
| 162 |
+
UNSHARDED = auto()
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@dataclass
|
| 166 |
+
class ParamModuleInfo:
|
| 167 |
+
"""
|
| 168 |
+
For a parameter, this stores the module and the parameter name to be able
|
| 169 |
+
to do a parameter swap via ``setattr(module, param_name, ...)`` or to get
|
| 170 |
+
the parameter via ``getattr(module, param_name)``. We additionally save
|
| 171 |
+
shared modules and shared parameter names to update them accordingly.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
# Parameter names are unprefixed, e.g. "weight", not "lin.weight"
|
| 175 |
+
module: nn.Module
|
| 176 |
+
param_name: str
|
| 177 |
+
shared_modules: list[nn.Module] = field(default_factory=list)
|
| 178 |
+
shared_param_names: list[str] = field(default_factory=list)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@dataclass
|
| 182 |
+
class ExtensionsData:
|
| 183 |
+
# User-defined metadata passed from pre to post-all-gather
|
| 184 |
+
all_gather_metadata: Optional[Any] = None
|
| 185 |
+
# Save the all-gather input sizes to unflatten the all-gather outputs to ND
|
| 186 |
+
all_gather_input_sizes: Sequence[torch.Size] = () # ND
|
| 187 |
+
|
| 188 |
+
def clear(self):
|
| 189 |
+
self.all_gather_metadata = None
|
| 190 |
+
self.all_gather_input_sizes = ()
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class FSDPParam:
|
| 194 |
+
"""
|
| 195 |
+
This class manages a parameter with FSDP or FSDP variants applied,
|
| 196 |
+
implementing dim-0 per-parameter sharding.
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
orig_dtype: torch.dtype
|
| 200 |
+
param_dtype: Optional[torch.dtype]
|
| 201 |
+
reduce_dtype: Optional[torch.dtype]
|
| 202 |
+
_orig_size: torch.Size # ND
|
| 203 |
+
sharded_size: torch.Size # ND
|
| 204 |
+
contiguous_sharded_stride: tuple[int, ...]
|
| 205 |
+
padded_sharded_param_size: torch.Size # ND
|
| 206 |
+
sharded_post_forward_size: torch.Size # ND
|
| 207 |
+
contiguous_sharded_post_forward_stride: tuple[int, ...]
|
| 208 |
+
_sharded_param_data: torch.Tensor # 1D
|
| 209 |
+
sharded_param: nn.Parameter # ND
|
| 210 |
+
_sharded_post_forward_param_data: Optional[torch.Tensor] # 1D
|
| 211 |
+
_sharded_post_forward_param: Optional[nn.Parameter] # ND
|
| 212 |
+
_unsharded_param: nn.Parameter # ND
|
| 213 |
+
unsharded_accumulated_grad: Optional[torch.Tensor] # ND
|
| 214 |
+
_sharding_spec: DTensorSpec
|
| 215 |
+
# DTensor attributes (only defined for DTensor `param`):
|
| 216 |
+
_tp_spec: DTensorSpec
|
| 217 |
+
all_gather_outputs: list[torch.Tensor] # 1D
|
| 218 |
+
# All-gather extension attributes
|
| 219 |
+
_extensions_data: ExtensionsData
|
| 220 |
+
_unsharded_inner_tensors: list[torch.Tensor]
|
| 221 |
+
|
| 222 |
+
def __init__(
|
| 223 |
+
self,
|
| 224 |
+
param: nn.Parameter,
|
| 225 |
+
module_info: ParamModuleInfo,
|
| 226 |
+
mesh_info: FSDPMeshInfo,
|
| 227 |
+
post_forward_mesh_info: Optional[FSDPMeshInfo],
|
| 228 |
+
device: torch.device,
|
| 229 |
+
shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]],
|
| 230 |
+
mp_policy: MixedPrecisionPolicy,
|
| 231 |
+
offload_policy: OffloadPolicy,
|
| 232 |
+
):
|
| 233 |
+
self._module_info: ParamModuleInfo = module_info
|
| 234 |
+
self.mesh_info = mesh_info
|
| 235 |
+
self.post_forward_mesh_info = post_forward_mesh_info
|
| 236 |
+
self.device = device
|
| 237 |
+
self.mp_policy = mp_policy
|
| 238 |
+
self.offload_to_cpu: bool = isinstance(offload_policy, CPUOffloadPolicy)
|
| 239 |
+
self.pin_memory = (
|
| 240 |
+
self.offload_to_cpu and cast(CPUOffloadPolicy, offload_policy).pin_memory
|
| 241 |
+
)
|
| 242 |
+
self.grad_offload_event: Optional[torch.Event] = None
|
| 243 |
+
self._init_sharded_param(param, device, shard_placement_fn)
|
| 244 |
+
if self.post_forward_mesh_info:
|
| 245 |
+
self._init_sharded_post_forward_param_metadata(param)
|
| 246 |
+
self._init_extensions()
|
| 247 |
+
self.all_gather_outputs: list[torch.Tensor] = []
|
| 248 |
+
self.unsharded_accumulated_grad = None
|
| 249 |
+
self._param_fqn: Optional[str] = None # prefixed from root module
|
| 250 |
+
# TODO: Remove this padding logic once DTensor pads the local tensor:
|
| 251 |
+
# https://github.com/pytorch/pytorch/issues/113045
|
| 252 |
+
self._post_load_hook_handle = (
|
| 253 |
+
module_info.module.register_load_state_dict_post_hook(
|
| 254 |
+
lambda *args, **kwargs: self.reset_sharded_param()
|
| 255 |
+
)
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
@torch.no_grad()
|
| 259 |
+
def _init_sharded_param(
|
| 260 |
+
self,
|
| 261 |
+
param: nn.Parameter,
|
| 262 |
+
device: torch.device,
|
| 263 |
+
shard_placement_fn: Optional[Callable],
|
| 264 |
+
):
|
| 265 |
+
if param.device != device and param.device.type != "meta":
|
| 266 |
+
raise AssertionError(
|
| 267 |
+
f"Expects the parameter to already be moved to device {device} but got {param.device}"
|
| 268 |
+
)
|
| 269 |
+
if not param.is_contiguous():
|
| 270 |
+
raise NotImplementedError(
|
| 271 |
+
f"FSDP does not support non-contiguous parameters yet: {param.shape=} {param.stride()=}"
|
| 272 |
+
)
|
| 273 |
+
fsdp_placement = shard_placement_fn(param) if shard_placement_fn else None
|
| 274 |
+
if fsdp_placement is None:
|
| 275 |
+
fsdp_placement = Shard(0)
|
| 276 |
+
elif fsdp_placement.dim < 0:
|
| 277 |
+
fsdp_placement = Shard(fsdp_placement.dim + param.ndim)
|
| 278 |
+
assert isinstance(fsdp_placement, Shard), f"{fsdp_placement}"
|
| 279 |
+
self.fsdp_placement = fsdp_placement
|
| 280 |
+
shard_dim = fsdp_placement.dim
|
| 281 |
+
# TODO: Replace the sharded DTensor parameter construction logic with
|
| 282 |
+
# `distribute_tensor` after https://github.com/pytorch/pytorch/issues/116101
|
| 283 |
+
# TODO: Simplify the following sharded parameter padding logic after
|
| 284 |
+
# https://github.com/pytorch/pytorch/issues/113045
|
| 285 |
+
self.is_dtensor = isinstance(param, DTensor)
|
| 286 |
+
if self.is_dtensor:
|
| 287 |
+
self._tp_spec = cast(DTensor, param)._spec
|
| 288 |
+
dp_mesh, tp_mesh = (self.mesh_info.mesh, self._tp_spec.mesh)
|
| 289 |
+
dp_global_mesh = _mesh_resources.get_root_mesh(dp_mesh)
|
| 290 |
+
tp_global_mesh = _mesh_resources.get_root_mesh(tp_mesh)
|
| 291 |
+
if dp_global_mesh != tp_global_mesh or (
|
| 292 |
+
dp_global_mesh is None or tp_global_mesh is None
|
| 293 |
+
):
|
| 294 |
+
raise AssertionError(
|
| 295 |
+
"FSDP requires the DP and TP mesh to have the same parent mesh but got: \n"
|
| 296 |
+
f"DP's global mesh: {dp_global_mesh}\nTP's global mesh: {tp_global_mesh}"
|
| 297 |
+
)
|
| 298 |
+
name_dims_error = "FSDP requires named DeviceMesh dims for ND parallelism"
|
| 299 |
+
assert dp_mesh.mesh_dim_names is not None, name_dims_error
|
| 300 |
+
assert tp_mesh.mesh_dim_names is not None, name_dims_error
|
| 301 |
+
submesh_names = dp_mesh.mesh_dim_names + tp_mesh.mesh_dim_names
|
| 302 |
+
self._spmd_mesh = dp_global_mesh[submesh_names]
|
| 303 |
+
if len(self._tp_spec.placements) != 1:
|
| 304 |
+
raise NotImplementedError(
|
| 305 |
+
f"FSDP only supports 1D TP, not {self._tp_spec.placements}"
|
| 306 |
+
)
|
| 307 |
+
split_factor = self._tp_spec.num_shards_map[shard_dim]
|
| 308 |
+
assert 2 <= self._spmd_mesh.ndim <= 3, (
|
| 309 |
+
f"_spmd_mesh.ndim can only be 2 or 3 but got {self._spmd_mesh.ndim}."
|
| 310 |
+
)
|
| 311 |
+
self._spmd_placements: tuple[Placement, ...]
|
| 312 |
+
dp_shard_tp_placement = (
|
| 313 |
+
(
|
| 314 |
+
_StridedShard(shard_dim, split_factor=split_factor)
|
| 315 |
+
if split_factor > 1
|
| 316 |
+
else fsdp_placement
|
| 317 |
+
),
|
| 318 |
+
self._tp_spec.placements[0],
|
| 319 |
+
)
|
| 320 |
+
if self._spmd_mesh.ndim == 2:
|
| 321 |
+
self._spmd_placements = dp_shard_tp_placement
|
| 322 |
+
else:
|
| 323 |
+
assert self.mesh_info.replicate_mesh_dim == 0
|
| 324 |
+
self._spmd_placements = (Replicate(),) + dp_shard_tp_placement
|
| 325 |
+
self._sharding_spec = DTensorSpec(
|
| 326 |
+
self._spmd_mesh,
|
| 327 |
+
self._spmd_placements,
|
| 328 |
+
tensor_meta=self._tp_spec.tensor_meta,
|
| 329 |
+
)
|
| 330 |
+
param_data = cast(DTensor, param)._local_tensor
|
| 331 |
+
else:
|
| 332 |
+
self._spmd_mesh = self.mesh_info.mesh
|
| 333 |
+
if isinstance(self.mesh_info, HSDPMeshInfo):
|
| 334 |
+
self._spmd_placements = (Replicate(), fsdp_placement)
|
| 335 |
+
else:
|
| 336 |
+
self._spmd_placements = (fsdp_placement,)
|
| 337 |
+
self._sharding_spec = DTensorSpec(
|
| 338 |
+
self._spmd_mesh,
|
| 339 |
+
self._spmd_placements,
|
| 340 |
+
tensor_meta=TensorMeta(param.size(), param.stride(), param.dtype),
|
| 341 |
+
)
|
| 342 |
+
param_data = param
|
| 343 |
+
assert param_data.is_contiguous(), f"{param_data.shape=} {param_data.stride()=}"
|
| 344 |
+
shard_dim = fsdp_placement.dim
|
| 345 |
+
if shard_dim >= param_data.ndim:
|
| 346 |
+
raise AssertionError(
|
| 347 |
+
f"Shard dim {shard_dim} is invalid for {param_data.ndim}D tensor: {param.shape}"
|
| 348 |
+
)
|
| 349 |
+
self._orig_size = param_data.size()
|
| 350 |
+
self._contiguous_orig_stride = make_contiguous_strides_for(self._orig_size)
|
| 351 |
+
shard_rank = self.mesh_info.shard_mesh_rank
|
| 352 |
+
shard_world_size = self.mesh_info.shard_mesh_size
|
| 353 |
+
if shard_dim > 0 and param_data.size(shard_dim) % shard_world_size != 0:
|
| 354 |
+
# If sharding on nonzero dim, require even sharding for now because
|
| 355 |
+
# the uneven sharding (1) requires extra copies before/after FSDP
|
| 356 |
+
# collectives and (2) introduces extra complexity to handle padding
|
| 357 |
+
# and unpadding
|
| 358 |
+
raise NotImplementedError(
|
| 359 |
+
f"FSDP does not support uneven sharding on dim {shard_dim}: "
|
| 360 |
+
f"{param_data.size()} (world size: {shard_world_size})"
|
| 361 |
+
)
|
| 362 |
+
chunks = _chunk_with_empty(param_data, shard_world_size, dim=shard_dim)
|
| 363 |
+
sharded_param = chunks[shard_rank]
|
| 364 |
+
self.sharded_size = _get_dim_chunked_size(
|
| 365 |
+
sharded_param, param_data.size(), dim=shard_dim
|
| 366 |
+
)
|
| 367 |
+
self.contiguous_sharded_stride = make_contiguous_strides_for(self.sharded_size)
|
| 368 |
+
padded_sharded_size = chunks[0].size() # 0th always padded
|
| 369 |
+
self.padded_sharded_param_size = padded_sharded_size
|
| 370 |
+
# Pre-pad the sharded parameter to avoid padding before all-gather
|
| 371 |
+
padded_sharded_param = param_data.new_zeros(padded_sharded_size)
|
| 372 |
+
if sharded_param.numel() > 0:
|
| 373 |
+
padded_sharded_param.narrow(
|
| 374 |
+
dim=shard_dim, start=0, length=sharded_param.size(shard_dim)
|
| 375 |
+
).copy_(sharded_param)
|
| 376 |
+
if self.offload_to_cpu and not padded_sharded_param.is_meta:
|
| 377 |
+
padded_sharded_param = padded_sharded_param.cpu()
|
| 378 |
+
if self.pin_memory:
|
| 379 |
+
padded_sharded_param = padded_sharded_param.pin_memory(
|
| 380 |
+
device=self.device
|
| 381 |
+
)
|
| 382 |
+
self._sharded_param_data = padded_sharded_param.view(-1)
|
| 383 |
+
length = sharded_param.size(shard_dim) if sharded_param.numel() > 0 else 0
|
| 384 |
+
sharded_param = padded_sharded_param.narrow(
|
| 385 |
+
dim=shard_dim, start=0, length=length
|
| 386 |
+
)
|
| 387 |
+
assert sharded_param.is_contiguous(), f"{self.fsdp_placement=}"
|
| 388 |
+
self.sharded_param = nn.Parameter(self.to_sharded_dtensor(sharded_param))
|
| 389 |
+
self.sharded_param.requires_grad_(param.requires_grad)
|
| 390 |
+
# Let `param_data` be freed normally when its ref count reaches 0 when
|
| 391 |
+
# the `fully_shard` call returns to allow provided parameters to alias
|
| 392 |
+
self._setattr_on_modules(self.sharded_param)
|
| 393 |
+
self.sharded_state = ShardedState.SHARDED
|
| 394 |
+
|
| 395 |
+
def _init_sharded_post_forward_param_metadata(self, param: torch.Tensor) -> None:
|
| 396 |
+
mesh_info = self.post_forward_mesh_info
|
| 397 |
+
assert mesh_info is not None # mypy
|
| 398 |
+
param_data = param._local_tensor if isinstance(param, DTensor) else param
|
| 399 |
+
chunks = _chunk_with_empty(param_data, mesh_info.shard_mesh_size, dim=0)
|
| 400 |
+
self.sharded_post_forward_size = _get_dim_chunked_size(
|
| 401 |
+
chunks[mesh_info.shard_mesh_rank],
|
| 402 |
+
param_data.size(),
|
| 403 |
+
dim=self.fsdp_placement.dim,
|
| 404 |
+
)
|
| 405 |
+
self.contiguous_sharded_post_forward_stride = make_contiguous_strides_for(
|
| 406 |
+
self.sharded_post_forward_size
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
def init_dtype_attrs(self, mp_policy: MixedPrecisionPolicy):
|
| 410 |
+
param_dtype, reduce_dtype = (mp_policy.param_dtype, mp_policy.reduce_dtype)
|
| 411 |
+
self.orig_dtype = self.sharded_param.dtype
|
| 412 |
+
# Clamp `reduce_dtype` to `None` if no casting is required: since
|
| 413 |
+
# gradients are computed in `param_dtype`, if `reduce_dtype` matches,
|
| 414 |
+
# then we do not need extra casting
|
| 415 |
+
if reduce_dtype == param_dtype:
|
| 416 |
+
reduce_dtype = None
|
| 417 |
+
# Clamp `param_dtype` to `None` if no casting is required
|
| 418 |
+
if param_dtype == self.orig_dtype:
|
| 419 |
+
param_dtype = None
|
| 420 |
+
self.param_dtype = param_dtype
|
| 421 |
+
self.reduce_dtype = reduce_dtype
|
| 422 |
+
# None indicates that the mixed precision is not enabled
|
| 423 |
+
|
| 424 |
+
def _init_extensions(self) -> None:
|
| 425 |
+
inner_tensor = self._sharded_local_tensor
|
| 426 |
+
has_fsdp_pre_all_gather = hasattr(inner_tensor, "fsdp_pre_all_gather")
|
| 427 |
+
has_fsdp_post_all_gather = hasattr(inner_tensor, "fsdp_post_all_gather")
|
| 428 |
+
if has_fsdp_pre_all_gather != has_fsdp_post_all_gather:
|
| 429 |
+
raise AssertionError(
|
| 430 |
+
"Both fsdp_pre_all_gather and fsdp_post_all_gather should be defined "
|
| 431 |
+
f"if using all-gather extensions: {inner_tensor}"
|
| 432 |
+
)
|
| 433 |
+
if has_fsdp_pre_all_gather:
|
| 434 |
+
self._extensions_data = ExtensionsData()
|
| 435 |
+
self._unsharded_inner_tensors: list[torch.Tensor] = []
|
| 436 |
+
|
| 437 |
+
def init_all_gather_outputs(
|
| 438 |
+
self,
|
| 439 |
+
all_gather_input_numels: list[int],
|
| 440 |
+
all_gather_input_dtypes: list[torch.dtype],
|
| 441 |
+
world_size: int,
|
| 442 |
+
device: torch.device,
|
| 443 |
+
force_recreate: bool = False,
|
| 444 |
+
):
|
| 445 |
+
if not force_recreate and len(self.all_gather_outputs) > 0:
|
| 446 |
+
return # already initialized
|
| 447 |
+
self.all_gather_outputs = [
|
| 448 |
+
torch.empty(torch.Size([numel * world_size]), dtype=dtype, device=device)
|
| 449 |
+
for numel, dtype in zip(all_gather_input_numels, all_gather_input_dtypes)
|
| 450 |
+
]
|
| 451 |
+
|
| 452 |
+
def init_unsharded_param(self):
|
| 453 |
+
"""
|
| 454 |
+
[Note: Invariants for torch.compile Traceable FSDP2]
|
| 455 |
+
1. Under compile, we always re-populate the content of `self._unsharded_param`
|
| 456 |
+
per AllGather using the slow path.
|
| 457 |
+
2. Under compile, we always recreate `self.all_gather_outputs` per AllGather.
|
| 458 |
+
This is to ensure the buffer creation is internal to the graph and
|
| 459 |
+
avoid `self.all_gather_outputs` being captured as a graph input.
|
| 460 |
+
3. Under compile, at the end of `free_unsharded_param()`, we always clean up
|
| 461 |
+
`self.all_gather_outputs` and `self._unsharded_inner_tensors`,
|
| 462 |
+
to avoid them being captured as graph output.
|
| 463 |
+
|
| 464 |
+
With these invariants, only these tensors will be inputs to the graph:
|
| 465 |
+
- Sharded parameters
|
| 466 |
+
- Placeholders for the `self._unsharded_param` nn.Parameter
|
| 467 |
+
"""
|
| 468 |
+
if not compiled_autograd_enabled() and hasattr(
|
| 469 |
+
self, "_unsharded_param"
|
| 470 |
+
): # after the 1st all-gather
|
| 471 |
+
inner_tensor = self._sharded_local_tensor
|
| 472 |
+
if not hasattr(inner_tensor, "fsdp_post_all_gather"):
|
| 473 |
+
return # already initialized
|
| 474 |
+
for tensor in self._unsharded_inner_tensors:
|
| 475 |
+
alloc_storage(tensor)
|
| 476 |
+
all_gather_outputs = self._unflatten_all_gather_outputs()
|
| 477 |
+
inner_tensor.fsdp_post_all_gather(
|
| 478 |
+
all_gather_outputs,
|
| 479 |
+
self._extensions_data.all_gather_metadata,
|
| 480 |
+
self.param_dtype or self.orig_dtype,
|
| 481 |
+
out=self._unsharded_param,
|
| 482 |
+
)
|
| 483 |
+
self._extensions_data.clear()
|
| 484 |
+
return
|
| 485 |
+
inner_tensor = self._sharded_local_tensor
|
| 486 |
+
if not compiled_autograd_enabled() and hasattr(
|
| 487 |
+
inner_tensor, "fsdp_post_all_gather"
|
| 488 |
+
):
|
| 489 |
+
all_gather_outputs = self._unflatten_all_gather_outputs()
|
| 490 |
+
(
|
| 491 |
+
unsharded_tensor,
|
| 492 |
+
self._unsharded_inner_tensors,
|
| 493 |
+
) = inner_tensor.fsdp_post_all_gather(
|
| 494 |
+
all_gather_outputs,
|
| 495 |
+
self._extensions_data.all_gather_metadata,
|
| 496 |
+
self.param_dtype or self.orig_dtype,
|
| 497 |
+
)
|
| 498 |
+
self._extensions_data.clear()
|
| 499 |
+
else:
|
| 500 |
+
# For the default path (no post-all-gather), the all-gather output
|
| 501 |
+
# gives the unsharded parameter data directly
|
| 502 |
+
assert len(self.all_gather_outputs) == 1, f"{len(self.all_gather_outputs)}"
|
| 503 |
+
unsharded_tensor = self.all_gather_outputs[0]
|
| 504 |
+
unsharded_param = torch.as_strided(
|
| 505 |
+
unsharded_tensor,
|
| 506 |
+
self._orig_size,
|
| 507 |
+
self._contiguous_orig_stride,
|
| 508 |
+
storage_offset=0,
|
| 509 |
+
)
|
| 510 |
+
if self.is_dtensor:
|
| 511 |
+
unsharded_param = _from_local_no_grad(unsharded_param, self._tp_spec)
|
| 512 |
+
if hasattr(self, "_unsharded_param"):
|
| 513 |
+
assert compiled_autograd_enabled()
|
| 514 |
+
with (
|
| 515 |
+
torch.no_grad(),
|
| 516 |
+
torch.autograd._unsafe_preserve_version_counter(self._unsharded_param),
|
| 517 |
+
):
|
| 518 |
+
# NOTE: Under compile, if an unsharded param goes through
|
| 519 |
+
# resize_(full) -> copy_ -> resize_(0) pattern, we will remove those
|
| 520 |
+
# resize_ and copy_ ops in a compiler graph pass
|
| 521 |
+
# `remove_fsdp2_unsharded_param_graph_input_usage` to recover performance.
|
| 522 |
+
self._unsharded_param.untyped_storage().resize_(
|
| 523 |
+
self._unsharded_param.numel() * self._unsharded_param.itemsize
|
| 524 |
+
)
|
| 525 |
+
torch.ops.fsdp.copy_(self._unsharded_param, unsharded_param)
|
| 526 |
+
else:
|
| 527 |
+
self._unsharded_param = nn.Parameter(
|
| 528 |
+
unsharded_param, requires_grad=self.sharded_param.requires_grad
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
def _unflatten_all_gather_outputs(self) -> tuple[torch.Tensor, ...]:
|
| 532 |
+
return tuple(
|
| 533 |
+
t.view(-1, *s[1:])
|
| 534 |
+
for t, s in zip(
|
| 535 |
+
self.all_gather_outputs, self._extensions_data.all_gather_input_sizes
|
| 536 |
+
)
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
def to_sharded(self) -> None:
|
| 540 |
+
self._setattr_on_modules(self.sharded_param)
|
| 541 |
+
self.free_unsharded_param()
|
| 542 |
+
self.sharded_state = ShardedState.SHARDED
|
| 543 |
+
|
| 544 |
+
def to_sharded_post_forward(self) -> None:
|
| 545 |
+
if self.is_dtensor:
|
| 546 |
+
raise NotImplementedError(
|
| 547 |
+
"Resharding to smaller mesh with TP is not supported yet"
|
| 548 |
+
)
|
| 549 |
+
self._assert_in_states(ShardedState.UNSHARDED)
|
| 550 |
+
assert self.post_forward_mesh_info is not None # mypy
|
| 551 |
+
assert len(self.all_gather_outputs) == 1
|
| 552 |
+
shard_world_size = self.post_forward_mesh_info.shard_mesh_size
|
| 553 |
+
if (numel := self.all_gather_outputs[0].numel()) % shard_world_size != 0:
|
| 554 |
+
_raise_assert_with_print(
|
| 555 |
+
f"All-gather output size ({numel}) must be divisible by the shard "
|
| 556 |
+
f"world size ({shard_world_size})"
|
| 557 |
+
)
|
| 558 |
+
shard_rank = self.post_forward_mesh_info.shard_mesh_rank
|
| 559 |
+
sharded_numel = numel // shard_world_size
|
| 560 |
+
self._sharded_post_forward_param_data = (
|
| 561 |
+
self.all_gather_outputs[0].narrow(
|
| 562 |
+
0, sharded_numel * shard_rank, sharded_numel
|
| 563 |
+
)
|
| 564 |
+
).clone() # clone to be able to free all-gather output
|
| 565 |
+
sharded_post_forward_tensor = torch.as_strided(
|
| 566 |
+
self._sharded_post_forward_param_data,
|
| 567 |
+
size=self.sharded_post_forward_size,
|
| 568 |
+
stride=self.contiguous_sharded_post_forward_stride,
|
| 569 |
+
storage_offset=0,
|
| 570 |
+
)
|
| 571 |
+
self._sharded_post_forward_param = nn.Parameter(
|
| 572 |
+
self.to_sharded_post_forward_dtensor(sharded_post_forward_tensor)
|
| 573 |
+
)
|
| 574 |
+
self._setattr_on_modules(self._sharded_post_forward_param)
|
| 575 |
+
self.free_unsharded_param()
|
| 576 |
+
self.sharded_state = ShardedState.SHARDED_POST_FORWARD
|
| 577 |
+
|
| 578 |
+
def to_unsharded(self) -> None:
|
| 579 |
+
# Assume that the data has been allocated and all-gathered
|
| 580 |
+
set_requires_grad_if_needed(self.sharded_param, self._unsharded_param)
|
| 581 |
+
self._setattr_on_modules(self._unsharded_param)
|
| 582 |
+
if self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
|
| 583 |
+
# The data is allocated in the default stream via the post-forward
|
| 584 |
+
# reshard and must be kept alive for the next all-gather copy-in.
|
| 585 |
+
# Since we call this method after the copy-out, the data's lifetime
|
| 586 |
+
# is ensured without further synchronization.
|
| 587 |
+
self._sharded_post_forward_param = None
|
| 588 |
+
self._sharded_post_forward_param_data = None # free
|
| 589 |
+
self.sharded_state = ShardedState.UNSHARDED
|
| 590 |
+
|
| 591 |
+
def _setattr_on_modules(self, param: nn.Parameter) -> None:
|
| 592 |
+
unsafe_setattr_param(
|
| 593 |
+
self._module_info.module, self._module_info.param_name, param
|
| 594 |
+
)
|
| 595 |
+
for shared_module, shared_param_name in zip(
|
| 596 |
+
self._module_info.shared_modules, self._module_info.shared_param_names
|
| 597 |
+
):
|
| 598 |
+
unsafe_setattr_param(shared_module, shared_param_name, param)
|
| 599 |
+
|
| 600 |
+
def to_sharded_dtensor(self, tensor: torch.Tensor) -> DTensor:
|
| 601 |
+
"""
|
| 602 |
+
Converts a local tensor representing either the sharded parameter or
|
| 603 |
+
sharded gradient to DTensor.
|
| 604 |
+
"""
|
| 605 |
+
if tensor.shape != self.sharded_size:
|
| 606 |
+
_raise_assert_with_print(
|
| 607 |
+
f"Expects size {self.sharded_size} but got {tensor.shape}"
|
| 608 |
+
)
|
| 609 |
+
return _from_local_no_grad(
|
| 610 |
+
tensor,
|
| 611 |
+
self._sharding_spec,
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
def to_sharded_post_forward_dtensor(self, tensor: torch.Tensor) -> DTensor:
|
| 615 |
+
if tensor.shape != self.sharded_post_forward_size:
|
| 616 |
+
_raise_assert_with_print(
|
| 617 |
+
f"Expects size {self.sharded_post_forward_size} but got {tensor.shape}"
|
| 618 |
+
)
|
| 619 |
+
assert isinstance(self.post_forward_mesh_info, HSDPMeshInfo)
|
| 620 |
+
# TODO: Prefer this DTensor to be read-only and generalize the
|
| 621 |
+
# placement once we support TP.
|
| 622 |
+
post_forward_sharding_spec = DTensorSpec(
|
| 623 |
+
self.post_forward_mesh_info.mesh,
|
| 624 |
+
(Replicate(), Shard(0)),
|
| 625 |
+
tensor_meta=self._sharding_spec.tensor_meta,
|
| 626 |
+
)
|
| 627 |
+
return _from_local_no_grad(tensor, post_forward_sharding_spec)
|
| 628 |
+
|
| 629 |
+
def to_accumulated_grad_if_needed(self) -> None:
|
| 630 |
+
# Access `_unsharded_param` to bypass the sharded state check since we
|
| 631 |
+
# prefer to reshard before upcasting the gradient to save memory
|
| 632 |
+
if (
|
| 633 |
+
self.reduce_dtype is None
|
| 634 |
+
or self._unsharded_param.grad is None
|
| 635 |
+
or self._unsharded_param.grad.dtype == self.reduce_dtype
|
| 636 |
+
):
|
| 637 |
+
return
|
| 638 |
+
unsharded_grad = self._unsharded_param.grad
|
| 639 |
+
self._unsharded_param.grad = None
|
| 640 |
+
self.unsharded_accumulated_grad = unsharded_grad.to(self.reduce_dtype)
|
| 641 |
+
|
| 642 |
+
def accumulate_unsharded_grad_if_needed(self) -> None:
|
| 643 |
+
if (
|
| 644 |
+
self.unsharded_accumulated_grad is not None
|
| 645 |
+
and self.unsharded_param.grad is not None
|
| 646 |
+
):
|
| 647 |
+
self.unsharded_accumulated_grad += self.unsharded_param.grad
|
| 648 |
+
self.unsharded_param.grad = None
|
| 649 |
+
|
| 650 |
+
def alloc_all_gather_outputs(self) -> None:
|
| 651 |
+
for tensor in self.all_gather_outputs:
|
| 652 |
+
alloc_storage(tensor)
|
| 653 |
+
|
| 654 |
+
def free_unsharded_param(self) -> None:
|
| 655 |
+
if compiled_autograd_enabled():
|
| 656 |
+
"""
|
| 657 |
+
Assumptions under compile:
|
| 658 |
+
- `self._unsharded_param` is NOT an alias of `self.all_gather_outputs`.
|
| 659 |
+
Instead, we resize `self._unsharded_param` storage size to full and then
|
| 660 |
+
explicitly *copy* the data from `self.all_gather_outputs` to `self._unsharded_param`
|
| 661 |
+
in `init_unsharded_param()`. (For full-graph FSDP2 case, we will then remove
|
| 662 |
+
the resize_ and copy_ ops in a compiler graph pass to recover performance.)
|
| 663 |
+
- `self.all_gather_outputs` and `self._unsharded_inner_tensors` are NOT
|
| 664 |
+
graph inputs. They are created within the graph and is guaranteed to be freed
|
| 665 |
+
by the end of the graph. They don't leak outside of the graph.
|
| 666 |
+
"""
|
| 667 |
+
self._unsharded_param.untyped_storage().resize_(0)
|
| 668 |
+
self.all_gather_outputs = []
|
| 669 |
+
self._unsharded_inner_tensors = []
|
| 670 |
+
else:
|
| 671 |
+
for tensor in itertools.chain(
|
| 672 |
+
self.all_gather_outputs, self._unsharded_inner_tensors
|
| 673 |
+
):
|
| 674 |
+
free_storage(tensor)
|
| 675 |
+
|
| 676 |
+
@property
|
| 677 |
+
def all_gather_inputs(self) -> list[torch.Tensor]: # 1D
|
| 678 |
+
self._assert_in_states(ShardedState.SHARDED, ShardedState.SHARDED_POST_FORWARD)
|
| 679 |
+
if self.sharded_state == ShardedState.SHARDED:
|
| 680 |
+
if not compiled_autograd_enabled() and hasattr(
|
| 681 |
+
self._sharded_local_tensor, "fsdp_pre_all_gather"
|
| 682 |
+
):
|
| 683 |
+
sharded_local_tensor = self._sharded_local_tensor
|
| 684 |
+
if self.offload_to_cpu:
|
| 685 |
+
sharded_local_tensor = sharded_local_tensor.to(
|
| 686 |
+
self.device, non_blocking=True
|
| 687 |
+
)
|
| 688 |
+
pre_all_gather_signature = inspect.signature(
|
| 689 |
+
sharded_local_tensor.fsdp_pre_all_gather
|
| 690 |
+
)
|
| 691 |
+
num_fn_params = len(pre_all_gather_signature.parameters)
|
| 692 |
+
# Old signature only passes mesh; keep for BC for now
|
| 693 |
+
assert num_fn_params in (
|
| 694 |
+
1,
|
| 695 |
+
5,
|
| 696 |
+
), (
|
| 697 |
+
f"Invalid fsdp_pre_all_gather: {pre_all_gather_signature}\n"
|
| 698 |
+
"Expects fsdp_pre_all_gather(self, mesh: DeviceMesh, "
|
| 699 |
+
"module: nn.Module, mp_policy: MixedPrecisionPolicy)"
|
| 700 |
+
)
|
| 701 |
+
if num_fn_params == 1:
|
| 702 |
+
(
|
| 703 |
+
all_gather_inputs,
|
| 704 |
+
self._extensions_data.all_gather_metadata,
|
| 705 |
+
) = sharded_local_tensor.fsdp_pre_all_gather(
|
| 706 |
+
self.shard_mesh_from_root
|
| 707 |
+
)
|
| 708 |
+
else:
|
| 709 |
+
(
|
| 710 |
+
all_gather_inputs,
|
| 711 |
+
self._extensions_data.all_gather_metadata,
|
| 712 |
+
) = sharded_local_tensor.fsdp_pre_all_gather(
|
| 713 |
+
self.shard_mesh_from_root,
|
| 714 |
+
self._orig_size,
|
| 715 |
+
self._contiguous_orig_stride,
|
| 716 |
+
self._module_info.module,
|
| 717 |
+
self.mp_policy,
|
| 718 |
+
)
|
| 719 |
+
if (
|
| 720 |
+
sharded_local_tensor.size() != self.padded_sharded_param_size
|
| 721 |
+
and any(
|
| 722 |
+
all_gather_input.size() != self.padded_sharded_param_size
|
| 723 |
+
for all_gather_input in all_gather_inputs
|
| 724 |
+
)
|
| 725 |
+
):
|
| 726 |
+
# NOTE: Since this error can only be raised on the
|
| 727 |
+
# ranks that have padding, this can manifest as a NCCL
|
| 728 |
+
# watchdog timeout, as the other ranks will not error.
|
| 729 |
+
raise AssertionError(
|
| 730 |
+
"When a parameter is unevenly sharded by FSDP "
|
| 731 |
+
f"(orig size={self._orig_size}, FSDP world size={self.mesh_info.mesh.size()}), "
|
| 732 |
+
"fsdp_pre_all_gather must return all-gather inputs with the padded sharded size "
|
| 733 |
+
f"{self.padded_sharded_param_size} but got {[t.size() for t in all_gather_inputs]}"
|
| 734 |
+
)
|
| 735 |
+
self._extensions_data.all_gather_input_sizes = [
|
| 736 |
+
t.size() for t in all_gather_inputs
|
| 737 |
+
]
|
| 738 |
+
return [t.view(-1) for t in all_gather_inputs]
|
| 739 |
+
sharded_param_data = self._sharded_param_data
|
| 740 |
+
if self.offload_to_cpu:
|
| 741 |
+
sharded_param_data = sharded_param_data.to(
|
| 742 |
+
self.device, non_blocking=True
|
| 743 |
+
)
|
| 744 |
+
return [_to_dtype_if_needed(sharded_param_data, self.param_dtype)]
|
| 745 |
+
elif self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
|
| 746 |
+
if not compiled_autograd_enabled() and hasattr(
|
| 747 |
+
self._sharded_local_tensor, "fsdp_pre_all_gather"
|
| 748 |
+
):
|
| 749 |
+
raise NotImplementedError
|
| 750 |
+
all_gather_input = _to_dtype_if_needed(
|
| 751 |
+
cast(torch.Tensor, self._sharded_post_forward_param_data),
|
| 752 |
+
self.param_dtype,
|
| 753 |
+
)
|
| 754 |
+
return [all_gather_input]
|
| 755 |
+
return [torch.empty(0)] # mypy
|
| 756 |
+
|
| 757 |
+
@property
|
| 758 |
+
def unsharded_param(self) -> nn.Parameter: # ND
|
| 759 |
+
return self._unsharded_param
|
| 760 |
+
|
| 761 |
+
@property
|
| 762 |
+
def unsharded_grad_data(self) -> torch.Tensor:
|
| 763 |
+
grad = self.unsharded_param.grad
|
| 764 |
+
assert grad is not None, "Expects unsharded_param.grad to not be None"
|
| 765 |
+
return self._get_grad_inner_tensor(grad)
|
| 766 |
+
|
| 767 |
+
@property
|
| 768 |
+
def unsharded_accumulated_grad_data(self) -> torch.Tensor:
|
| 769 |
+
grad = self.unsharded_accumulated_grad
|
| 770 |
+
assert grad is not None, "Expects unsharded_accumulated_grad to not be None"
|
| 771 |
+
return self._get_grad_inner_tensor(grad)
|
| 772 |
+
|
| 773 |
+
def _get_grad_inner_tensor(self, grad: torch.Tensor) -> torch.Tensor:
|
| 774 |
+
if self.is_dtensor:
|
| 775 |
+
if isinstance(grad, AsyncCollectiveTensor):
|
| 776 |
+
grad = grad.wait()
|
| 777 |
+
assert isinstance(grad, DTensor), f"{type(grad)}"
|
| 778 |
+
placements = self._tp_spec.placements
|
| 779 |
+
if placements != grad.placements:
|
| 780 |
+
assert len(self._tp_spec.placements) == len(grad.placements), (
|
| 781 |
+
f"{self._tp_spec=} {grad.placements=}"
|
| 782 |
+
)
|
| 783 |
+
grad = grad.redistribute(placements=placements)
|
| 784 |
+
grad = grad._local_tensor
|
| 785 |
+
return grad
|
| 786 |
+
|
| 787 |
+
@property
|
| 788 |
+
def _sharded_local_tensor(self) -> torch.Tensor:
|
| 789 |
+
return cast(DTensor, self.sharded_param)._local_tensor
|
| 790 |
+
|
| 791 |
+
@property
|
| 792 |
+
def shard_mesh(self):
|
| 793 |
+
mesh = self.mesh_info.mesh
|
| 794 |
+
if mesh.ndim == 1:
|
| 795 |
+
return mesh
|
| 796 |
+
elif mesh.ndim == 2:
|
| 797 |
+
assert mesh.mesh_dim_names is not None
|
| 798 |
+
return mesh[mesh.mesh_dim_names[-1]]
|
| 799 |
+
raise ValueError(f"Invalid mesh: {mesh}")
|
| 800 |
+
|
| 801 |
+
@property
|
| 802 |
+
def shard_mesh_from_root(self):
|
| 803 |
+
mesh = self.mesh_info.mesh
|
| 804 |
+
|
| 805 |
+
if mesh.ndim == 1:
|
| 806 |
+
return mesh
|
| 807 |
+
else:
|
| 808 |
+
assert mesh.mesh_dim_names is not None
|
| 809 |
+
shard_dim_name = mesh.mesh_dim_names[-1]
|
| 810 |
+
|
| 811 |
+
root_mesh = _mesh_resources.get_root_mesh(mesh)
|
| 812 |
+
return root_mesh[shard_dim_name]
|
| 813 |
+
|
| 814 |
+
def _assert_in_states(self, *states: ShardedState) -> None:
|
| 815 |
+
if self.sharded_state not in states:
|
| 816 |
+
_raise_assert_with_print(
|
| 817 |
+
f"Expects to be in one of {states}, not {self.sharded_state}"
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
+
def reset_sharded_param(self):
|
| 821 |
+
# For ops like `nn.Module._apply` or `load_state_dict(assign=True)`
|
| 822 |
+
# that change the sharded parameter tensor, we may need to re-pad the
|
| 823 |
+
# sharded local tensor and re-save the reference.
|
| 824 |
+
module_info = self._module_info
|
| 825 |
+
new_param = getattr(module_info.module, module_info.param_name)
|
| 826 |
+
if new_param is not self.sharded_param:
|
| 827 |
+
if torch.__future__.get_swap_module_params_on_conversion():
|
| 828 |
+
raise AssertionError(
|
| 829 |
+
f"Expects swap_tensors to preserve object but got {new_param} "
|
| 830 |
+
f"instead of {self.sharded_param}"
|
| 831 |
+
)
|
| 832 |
+
self.sharded_param = new_param
|
| 833 |
+
local_tensor = new_param._local_tensor
|
| 834 |
+
if local_tensor.is_meta:
|
| 835 |
+
return
|
| 836 |
+
updated_local_tensor = False
|
| 837 |
+
padded_sharded_size = self.padded_sharded_param_size
|
| 838 |
+
shard_dim = self.fsdp_placement.dim
|
| 839 |
+
length = local_tensor.size(shard_dim) if local_tensor.numel() > 0 else 0
|
| 840 |
+
if local_tensor.size() != padded_sharded_size:
|
| 841 |
+
assert shard_dim == 0, (
|
| 842 |
+
f"Shard({shard_dim}) requires even sharding: {local_tensor.size()=}"
|
| 843 |
+
)
|
| 844 |
+
padded_local_tensor = local_tensor.new_zeros(padded_sharded_size)
|
| 845 |
+
padded_local_tensor.narrow(dim=shard_dim, start=0, length=length).copy_(
|
| 846 |
+
local_tensor
|
| 847 |
+
)
|
| 848 |
+
local_tensor = padded_local_tensor
|
| 849 |
+
updated_local_tensor = True
|
| 850 |
+
if self.pin_memory and not local_tensor.is_pinned():
|
| 851 |
+
local_tensor = local_tensor.cpu().pin_memory(device=self.device)
|
| 852 |
+
updated_local_tensor = True
|
| 853 |
+
self._sharded_param_data = local_tensor.view(-1)
|
| 854 |
+
assert isinstance(self.sharded_param, DTensor) # mypy
|
| 855 |
+
if updated_local_tensor:
|
| 856 |
+
# Only change the local tensor object if needed
|
| 857 |
+
self.sharded_param._local_tensor = local_tensor.narrow(
|
| 858 |
+
dim=shard_dim, start=0, length=length
|
| 859 |
+
)
|
| 860 |
+
assert self.sharded_param._local_tensor.is_contiguous()
|
| 861 |
+
self._sharding_spec = self.sharded_param._spec
|
| 862 |
+
|
| 863 |
+
def __repr__(self):
|
| 864 |
+
return f"FSDPParam(fqn={self._param_fqn}, orig_size={self._orig_size})"
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
def alloc_storage(tensor: torch.Tensor) -> None:
|
| 868 |
+
size = tensor.numel() * tensor.itemsize
|
| 869 |
+
if (storage := tensor.untyped_storage()).size() != size:
|
| 870 |
+
storage.resize_(size)
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def free_storage(tensor: torch.Tensor) -> None:
|
| 874 |
+
if (storage := tensor.untyped_storage()).size() != 0:
|
| 875 |
+
storage.resize_(0)
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
# NOTE: These bypass `nn.Module.__setattr__` checks, which incur non-trivial
|
| 879 |
+
# CPU overhead, if the module did not override it. For FSDP, we know we do not
|
| 880 |
+
# need those checks when transitioning between sharded/unsharded parameters.
|
| 881 |
+
def unsafe_setattr_param(
|
| 882 |
+
module: nn.Module, param_name: str, param: nn.Parameter
|
| 883 |
+
) -> None:
|
| 884 |
+
if getattr(module.__setattr__, "__func__", None) is nn.Module.__setattr__:
|
| 885 |
+
module._parameters[param_name] = param
|
| 886 |
+
else: # slow path
|
| 887 |
+
setattr(module, param_name, param)
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def set_requires_grad_if_needed(
|
| 891 |
+
src_tensor: torch.Tensor, dst_tensor: torch.Tensor
|
| 892 |
+
) -> None:
|
| 893 |
+
# Only call `requires_grad_` if needed to avoid the Python <> C++ context
|
| 894 |
+
# switch overhead
|
| 895 |
+
if src_tensor.requires_grad != dst_tensor.requires_grad:
|
| 896 |
+
dst_tensor.requires_grad_(src_tensor.requires_grad)
|
_fsdp_param_group.py
ADDED
|
@@ -0,0 +1,769 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import contextlib
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Any, Callable, cast, NamedTuple, Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.distributed as dist
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
from torch.distributed.device_mesh import _get_device_handle
|
| 10 |
+
from torch.distributed.fsdp._common_utils import _named_parameters_with_duplicates
|
| 11 |
+
from torch.distributed.tensor import Shard
|
| 12 |
+
from torch.profiler import record_function
|
| 13 |
+
from torch.utils._pytree import tree_flatten, tree_unflatten
|
| 14 |
+
from torch.utils.hooks import RemovableHandle
|
| 15 |
+
|
| 16 |
+
from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
|
| 17 |
+
from ._fsdp_collectives import (
|
| 18 |
+
AllGatherResult,
|
| 19 |
+
foreach_all_gather,
|
| 20 |
+
foreach_all_gather_copy_out,
|
| 21 |
+
foreach_reduce,
|
| 22 |
+
)
|
| 23 |
+
from ._fsdp_common import (
|
| 24 |
+
compiled_autograd_enabled,
|
| 25 |
+
FSDPMeshInfo,
|
| 26 |
+
HSDPMeshInfo,
|
| 27 |
+
TrainingState,
|
| 28 |
+
)
|
| 29 |
+
from ._fsdp_param import FSDPParam, ParamModuleInfo, ShardedState
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.getLogger("torch.distributed.fsdp.fully_shard")
|
| 33 |
+
|
| 34 |
+
_ModuleToHandleDict = dict[nn.Module, RemovableHandle] # for state dict
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
[Note: Overlapping all-gather copy-in and all-gather]
|
| 39 |
+
For implicit forward prefetching, we want to overlap the next copy-in with the
|
| 40 |
+
current all-gather. We do so using a separate copy-in stream. However, since
|
| 41 |
+
we have the all-gather input as a view into the output, we must make sure to
|
| 42 |
+
copy into different memory from the current all-gather's output. Thus, we keep
|
| 43 |
+
a reference to the current all-gather's output and have the next FSDP parameter
|
| 44 |
+
group free it after its copy-in. Finally, we have the last FSDP state flush the
|
| 45 |
+
reference to avoid holding onto memory after forward.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class FSDPCommContext:
|
| 50 |
+
"""This has the communication state shared across FSDP states/parameter groups."""
|
| 51 |
+
|
| 52 |
+
def lazy_init(self, device: torch.device):
|
| 53 |
+
self.device_handle = _get_device_handle(device.type)
|
| 54 |
+
# Setting the all-gather/reduce-scatter streams to be higher priority
|
| 55 |
+
# can help avoid some issues where their copies in/out are delayed and
|
| 56 |
+
# block computation (this is different from high-pri NCCL streams)
|
| 57 |
+
high_priority = -1
|
| 58 |
+
# All-gather state and copy-in stream allow overlapping the next
|
| 59 |
+
# copy-in with the current all-gather in forward; copy-in overlaps with
|
| 60 |
+
# reduce-scatter in backward without the separate copy-in stream
|
| 61 |
+
self.all_gather_copy_in_stream = self.device_handle.Stream(
|
| 62 |
+
priority=high_priority
|
| 63 |
+
)
|
| 64 |
+
# All-gather stream allows overlapping next all-gather with current
|
| 65 |
+
# forward compute
|
| 66 |
+
self.all_gather_stream = self.device_handle.Stream(priority=high_priority)
|
| 67 |
+
# Reduce-scatter stream gives separate execution "thread" for post-
|
| 68 |
+
# backward logic like pre/post-gradient division and reduce-scatter
|
| 69 |
+
self.reduce_scatter_stream = self.device_handle.Stream(priority=high_priority)
|
| 70 |
+
# Run the HSDP all-reduces concurrently with all-gather/reduce-scatter
|
| 71 |
+
# since collectives use different network resources and can overlap
|
| 72 |
+
# in the typical intra-node sharding / inter-node replication case
|
| 73 |
+
self.all_reduce_stream = self.device_handle.Stream()
|
| 74 |
+
# All-gather/reduce-scatter states keep references to collective
|
| 75 |
+
# tensors produced in one stream and used in another and accompanying
|
| 76 |
+
# CUDA events for synchronization
|
| 77 |
+
self.all_gather_state: Optional[AllGatherState] = None
|
| 78 |
+
self.reduce_scatter_state: Optional[ReduceScatterState] = None
|
| 79 |
+
# Post-forward order for explicit backward prefetching
|
| 80 |
+
self.post_forward_order: list[FSDPParamGroup] = [] # will cause ref cycles
|
| 81 |
+
|
| 82 |
+
def get_all_gather_streams(
|
| 83 |
+
self, async_op: bool, training_state: TrainingState
|
| 84 |
+
) -> tuple[torch.Stream, torch.Stream]:
|
| 85 |
+
if not async_op and training_state in (
|
| 86 |
+
TrainingState.FORWARD,
|
| 87 |
+
TrainingState.PRE_BACKWARD,
|
| 88 |
+
):
|
| 89 |
+
# Use separate streams for implicit prefetching
|
| 90 |
+
return self.all_gather_copy_in_stream, self.all_gather_stream
|
| 91 |
+
current_stream = self.device_handle.current_stream()
|
| 92 |
+
return current_stream, current_stream
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# See [Note: Overlapping all-gather copy-in and all-gather]
|
| 96 |
+
class AllGatherState(NamedTuple):
|
| 97 |
+
all_gather_result: AllGatherResult
|
| 98 |
+
event: Optional[torch.Event] # all-gather copy-out
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class ReduceScatterState(NamedTuple):
|
| 102 |
+
reduce_scatter_input: torch.Tensor
|
| 103 |
+
event: Optional[torch.Event] # reduce-scatter event
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class AllReduceState(NamedTuple):
|
| 107 |
+
all_reduce_input: torch.Tensor
|
| 108 |
+
event: Optional[torch.Event] # all-reduce event
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class FSDPParamGroup:
|
| 112 |
+
"""This class represents a parameter group to communicate together."""
|
| 113 |
+
|
| 114 |
+
_orig_dtype: Optional[torch.dtype]
|
| 115 |
+
_reduce_dtype: Optional[torch.dtype]
|
| 116 |
+
|
| 117 |
+
def __init__(
|
| 118 |
+
self,
|
| 119 |
+
params: list[nn.Parameter],
|
| 120 |
+
modules: tuple[nn.Module, ...],
|
| 121 |
+
mesh_info: FSDPMeshInfo,
|
| 122 |
+
post_forward_mesh_info: Optional[FSDPMeshInfo],
|
| 123 |
+
device: torch.device,
|
| 124 |
+
shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]],
|
| 125 |
+
mp_policy: MixedPrecisionPolicy,
|
| 126 |
+
offload_policy: OffloadPolicy,
|
| 127 |
+
):
|
| 128 |
+
self.modules = modules # permit ref cycle because 1:1 lifetime
|
| 129 |
+
param_module_infos = _get_param_module_infos(params, modules)
|
| 130 |
+
|
| 131 |
+
self.fsdp_params = [
|
| 132 |
+
FSDPParam(
|
| 133 |
+
param,
|
| 134 |
+
module_info,
|
| 135 |
+
mesh_info,
|
| 136 |
+
post_forward_mesh_info,
|
| 137 |
+
device,
|
| 138 |
+
shard_placement_fn,
|
| 139 |
+
mp_policy,
|
| 140 |
+
offload_policy,
|
| 141 |
+
)
|
| 142 |
+
for param, module_info in zip(params, param_module_infos)
|
| 143 |
+
]
|
| 144 |
+
self.mesh_info = mesh_info
|
| 145 |
+
self.post_forward_mesh_info = post_forward_mesh_info
|
| 146 |
+
self.device = device
|
| 147 |
+
self.device_handle = _get_device_handle(device.type)
|
| 148 |
+
self.mp_policy = mp_policy
|
| 149 |
+
self.offload_policy = offload_policy
|
| 150 |
+
self._training_state = TrainingState.IDLE
|
| 151 |
+
# Group's sharded state always matches its parameters' sharded states
|
| 152 |
+
self._sharded_state = ShardedState.SHARDED
|
| 153 |
+
self._module_fqn: Optional[str] = None # prefixed from root module
|
| 154 |
+
# Only consider resetting sharded parameters once in lazy init since it
|
| 155 |
+
# can incur nontrivial overhead to reset them
|
| 156 |
+
self._reset_sharded_params: bool = False
|
| 157 |
+
|
| 158 |
+
# - Hook state
|
| 159 |
+
self._module_to_pre_save_state_dict_hook_handle: _ModuleToHandleDict = {}
|
| 160 |
+
self._module_to_pre_load_state_dict_hook_handle: _ModuleToHandleDict = {}
|
| 161 |
+
self._all_reduce_hook: Optional[Callable[[torch.Tensor], None]] = None
|
| 162 |
+
# Optional stream to run the user-defined all-reduce hook in
|
| 163 |
+
# Saved here and not in the comm. context because we allow the user to
|
| 164 |
+
# specify it, possibly at construction time before lazy init
|
| 165 |
+
self._all_reduce_hook_stream: Optional[torch.cuda.Stream] = None
|
| 166 |
+
|
| 167 |
+
# - Communication and communication/computation overlap
|
| 168 |
+
self.comm_ctx = FSDPCommContext()
|
| 169 |
+
# Group's indices in the shared post-forward order
|
| 170 |
+
self._post_forward_indices: list[int] = []
|
| 171 |
+
# Whether to reduce gradients at all (whether for FSDP or HSDP)
|
| 172 |
+
self.reduce_grads: bool = True
|
| 173 |
+
# Whether to all-reduce gradients for HSDP; only used if
|
| 174 |
+
# `self.reduce_grads` is true, in which case setting this to false
|
| 175 |
+
# means reduce-scatter but no all-reduce
|
| 176 |
+
self.all_reduce_grads: bool = True
|
| 177 |
+
# Whether to reshard parameters after backward (only useful for
|
| 178 |
+
# gradient accumulation)
|
| 179 |
+
self.reshard_after_backward: bool = True
|
| 180 |
+
# Optional custom factor for the gradient reduction op (e.g. to divide
|
| 181 |
+
# by a factor other than the world size)
|
| 182 |
+
self.gradient_divide_factor: Optional[float] = None
|
| 183 |
+
# Whether reduce-scatter and all-reduce should be issued using only
|
| 184 |
+
# summations, potentially with separate pre-/post-scaling.
|
| 185 |
+
self.force_sum_reduction_for_comms: bool = False
|
| 186 |
+
# `async_op` arg used for pre-forward/pre-backward unshard; can be
|
| 187 |
+
# overridden to only do explicit prefetching and avoid inter-stream
|
| 188 |
+
# fragmentation from using separate unshard streams
|
| 189 |
+
self.unshard_async_op: bool = False
|
| 190 |
+
# Whether to unshard in backward: can be overridden by the user if the
|
| 191 |
+
# parameters in this group are not needed for backward (e.g. embedding)
|
| 192 |
+
self.unshard_in_backward: bool = True
|
| 193 |
+
# Whether to (try to) use the ProcessGroup's allocate_tensor method for
|
| 194 |
+
# the staging buffers for collective comms.
|
| 195 |
+
self.allocate_memory_from_process_group = False
|
| 196 |
+
|
| 197 |
+
# - CUDA events for stream synchronization
|
| 198 |
+
# Holds the all-gather output buffer, sync objects, and metadata
|
| 199 |
+
self._all_gather_result: Optional[AllGatherResult] = None
|
| 200 |
+
# Holds the reduce-scatter/all-reduce view-out CUDA event that marks the end of
|
| 201 |
+
# the group's post-backward (e.g. reduce-scatter, all-reduce and div), which
|
| 202 |
+
# should be waited on at the end of backward
|
| 203 |
+
self._post_reduce_event: Optional[torch.Event] = None
|
| 204 |
+
# Holds the reshard-after-forward CUDA event when resharding to a
|
| 205 |
+
# different world size, which should be waited on in the next unshard
|
| 206 |
+
self._reshard_after_forward_event: Optional[torch.Event] = None
|
| 207 |
+
|
| 208 |
+
# Only for HSDP, if accumulating gradients without all-reduce, save the
|
| 209 |
+
# partial reduce output (only reduce-scattered but not all-reduced)
|
| 210 |
+
self._partial_reduce_output: Optional[torch.Tensor] = None
|
| 211 |
+
# Holds the all-reduce input and all-reduce event to keep it alive
|
| 212 |
+
# until the end of backward (critical when doing bf16 reduction with
|
| 213 |
+
# fp32 parameters since the all-reduce input is allocated in the RS
|
| 214 |
+
# stream and will have no refs to it after being upcast to fp32)
|
| 215 |
+
self._all_reduce_state: Optional[AllReduceState] = None
|
| 216 |
+
|
| 217 |
+
# Initialization #
|
| 218 |
+
def _init_mp_dtypes(self) -> None:
|
| 219 |
+
for fsdp_param in self.fsdp_params:
|
| 220 |
+
fsdp_param.init_dtype_attrs(self.mp_policy)
|
| 221 |
+
trainable_params: list[FSDPParam] = [
|
| 222 |
+
p for p in self.fsdp_params if p.sharded_param.requires_grad
|
| 223 |
+
]
|
| 224 |
+
orig_dtypes = {p.orig_dtype for p in trainable_params}
|
| 225 |
+
reduce_dtypes = {p.reduce_dtype for p in trainable_params}
|
| 226 |
+
if len(trainable_params) > 0 and len(orig_dtypes) != 1:
|
| 227 |
+
# Models may have no grad params
|
| 228 |
+
raise AssertionError(
|
| 229 |
+
f"FSDP expects uniform original parameter dtype but got {orig_dtypes}"
|
| 230 |
+
)
|
| 231 |
+
self._orig_dtype = next(iter(orig_dtypes)) if len(trainable_params) else None
|
| 232 |
+
if len(trainable_params) > 0 and len(reduce_dtypes) != 1:
|
| 233 |
+
# This can be relaxed if we issue one reduce-scatter per reduce
|
| 234 |
+
# dtype (but we would need a way for users to specify multiple
|
| 235 |
+
# reduce dtypes)
|
| 236 |
+
raise AssertionError(
|
| 237 |
+
f"FSDP expects uniform reduce dtype but got {reduce_dtypes}"
|
| 238 |
+
)
|
| 239 |
+
self._reduce_dtype = (
|
| 240 |
+
next(iter(reduce_dtypes)) if len(trainable_params) else None
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
def lazy_init(self):
|
| 244 |
+
# Lazy init should be idempotent
|
| 245 |
+
# Users may change or register parameters after construction time.
|
| 246 |
+
# For example, DoRA (https://arxiv.org/abs/2402.09353) initializes linear magnitudes based on
|
| 247 |
+
# other parameters (e.g. loaded from the state dict).
|
| 248 |
+
if not hasattr(self.comm_ctx, "device_handle"):
|
| 249 |
+
self.comm_ctx.device_handle = _get_device_handle(self.device.type)
|
| 250 |
+
if self.is_sharded and not self._reset_sharded_params:
|
| 251 |
+
for fsdp_param in self.fsdp_params:
|
| 252 |
+
fsdp_param.reset_sharded_param()
|
| 253 |
+
fsdp_param._init_extensions() # allow monkey patch after init
|
| 254 |
+
self._reset_sharded_params = True
|
| 255 |
+
self._validate_no_meta_params()
|
| 256 |
+
self._validate_cpu_offload_params()
|
| 257 |
+
# Initialize mixed precision attributes lazily in case the user changes
|
| 258 |
+
# the parameter dtypes after construction time but before forward
|
| 259 |
+
self._init_mp_dtypes()
|
| 260 |
+
self._register_state_dict_hooks()
|
| 261 |
+
|
| 262 |
+
# Runtime #
|
| 263 |
+
def unshard(self, async_op: bool = False):
|
| 264 |
+
if self._all_gather_result is not None: # already called, pending wait
|
| 265 |
+
return
|
| 266 |
+
if self.is_unsharded:
|
| 267 |
+
return # no-op
|
| 268 |
+
if (
|
| 269 |
+
not self.unshard_in_backward
|
| 270 |
+
and self._training_state == TrainingState.PRE_BACKWARD
|
| 271 |
+
):
|
| 272 |
+
return
|
| 273 |
+
if self._reshard_after_forward_event is not None:
|
| 274 |
+
# Resharded parameter data is allocated in the default stream and
|
| 275 |
+
# used in the all-gather streams
|
| 276 |
+
self._wait_all_gather_streams_on_event(self._reshard_after_forward_event)
|
| 277 |
+
self._reshard_after_forward_event = None
|
| 278 |
+
with record_function(self._with_fqn("FSDP::all_gather")):
|
| 279 |
+
self._all_gather_result = foreach_all_gather(
|
| 280 |
+
self.fsdp_params,
|
| 281 |
+
self._all_gather_process_group,
|
| 282 |
+
async_op,
|
| 283 |
+
*self.comm_ctx.get_all_gather_streams(async_op, self._training_state),
|
| 284 |
+
self.device,
|
| 285 |
+
self.allocate_memory_from_process_group,
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
def wait_for_unshard(self):
|
| 289 |
+
"""
|
| 290 |
+
1. In forward with implicit prefetching, to overlap the current copy-out
|
| 291 |
+
with the next all-gather, we save a reference to the current all-gather
|
| 292 |
+
result to free after the next copy-out.
|
| 293 |
+
2. Otherwise (explicit prefetching or in backward), we free the
|
| 294 |
+
all-gather result immediately after the current copy-out since we can
|
| 295 |
+
already overlap the current copy-out with the previous reduce-scatter.
|
| 296 |
+
"""
|
| 297 |
+
if not self._all_gather_result:
|
| 298 |
+
return # no preceding unshard
|
| 299 |
+
async_op = self._all_gather_result.all_gather_work is not None
|
| 300 |
+
if self._training_state == TrainingState.FORWARD: # implicit prefetch
|
| 301 |
+
if prev_all_gather_state := self.comm_ctx.all_gather_state:
|
| 302 |
+
self._wait_all_gather_streams_on_event(prev_all_gather_state.event)
|
| 303 |
+
self.comm_ctx.all_gather_state = None # free the all-gather result
|
| 304 |
+
with record_function(self._with_fqn("FSDP::all_gather_copy_out")):
|
| 305 |
+
foreach_all_gather_copy_out(
|
| 306 |
+
self._all_gather_result,
|
| 307 |
+
self.fsdp_params,
|
| 308 |
+
self._all_gather_process_group,
|
| 309 |
+
)
|
| 310 |
+
for fsdp_param in self.fsdp_params:
|
| 311 |
+
fsdp_param.init_unsharded_param()
|
| 312 |
+
self._to_unsharded()
|
| 313 |
+
all_gather_copy_out_event = self.device_handle.Event()
|
| 314 |
+
all_gather_copy_out_event.record()
|
| 315 |
+
if not async_op and self._training_state == TrainingState.FORWARD:
|
| 316 |
+
# Defer free to allow for overlap of this copy-out with next
|
| 317 |
+
# all-gather collective
|
| 318 |
+
self.comm_ctx.all_gather_state = AllGatherState(
|
| 319 |
+
self._all_gather_result, all_gather_copy_out_event
|
| 320 |
+
)
|
| 321 |
+
else:
|
| 322 |
+
self._wait_all_gather_streams_on_event(all_gather_copy_out_event)
|
| 323 |
+
self._all_gather_result = None # free unless saved in `all_gather_state`
|
| 324 |
+
|
| 325 |
+
def _wait_all_gather_streams_on_event(self, event: Optional[torch.Event]):
|
| 326 |
+
# Calling `unshard` before lazy init means streams are not initialized
|
| 327 |
+
if hasattr(self.comm_ctx, "all_gather_copy_in_stream") and event is not None:
|
| 328 |
+
self.comm_ctx.all_gather_copy_in_stream.wait_event(event)
|
| 329 |
+
if hasattr(self.comm_ctx, "all_gather_stream") and event is not None:
|
| 330 |
+
self.comm_ctx.all_gather_stream.wait_event(event)
|
| 331 |
+
|
| 332 |
+
def reshard(self):
|
| 333 |
+
if self._training_state == TrainingState.FORWARD:
|
| 334 |
+
if not self._reshard_after_forward:
|
| 335 |
+
return
|
| 336 |
+
if self._use_post_forward_mesh:
|
| 337 |
+
self._to_sharded_post_forward()
|
| 338 |
+
self._reshard_after_forward_event = self.device_handle.Event()
|
| 339 |
+
if self._reshard_after_forward_event is not None:
|
| 340 |
+
self._reshard_after_forward_event.record()
|
| 341 |
+
return
|
| 342 |
+
self._to_sharded()
|
| 343 |
+
|
| 344 |
+
def pre_forward(
|
| 345 |
+
self, module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
|
| 346 |
+
) -> tuple[tuple[Any, ...], dict[str, Any]]:
|
| 347 |
+
if not compiled_autograd_enabled():
|
| 348 |
+
logger.debug("%s", self._with_fqn("FSDP::pre_forward"))
|
| 349 |
+
with record_function(self._with_fqn("FSDP::pre_forward")):
|
| 350 |
+
self._training_state = TrainingState.FORWARD
|
| 351 |
+
self.unshard(self.unshard_async_op)
|
| 352 |
+
self.wait_for_unshard()
|
| 353 |
+
args, kwargs = self._register_post_backward_hook(args, kwargs)
|
| 354 |
+
return args, kwargs
|
| 355 |
+
|
| 356 |
+
def post_forward(self, module: nn.Module, input: Any, output: Any):
|
| 357 |
+
if not compiled_autograd_enabled():
|
| 358 |
+
logger.debug("%s", self._with_fqn("FSDP::post_forward"))
|
| 359 |
+
with record_function(self._with_fqn("FSDP::post_forward")):
|
| 360 |
+
self.reshard()
|
| 361 |
+
self._record_post_forward()
|
| 362 |
+
self._training_state = TrainingState.IDLE
|
| 363 |
+
return output
|
| 364 |
+
|
| 365 |
+
def _record_post_forward(self) -> None:
|
| 366 |
+
# Since a group has one pre-backward unshard for each forward call
|
| 367 |
+
# before the backward, we record each usage (with multiplicity)
|
| 368 |
+
post_forward_index = len(self.comm_ctx.post_forward_order)
|
| 369 |
+
self.comm_ctx.post_forward_order.append(self)
|
| 370 |
+
self._post_forward_indices.append(post_forward_index)
|
| 371 |
+
|
| 372 |
+
def pre_backward(self, default_prefetch: bool, *unused: Any):
|
| 373 |
+
if (
|
| 374 |
+
compiled_autograd_enabled()
|
| 375 |
+
and self._training_state == TrainingState.PRE_BACKWARD
|
| 376 |
+
):
|
| 377 |
+
# Traceable FSDP2 cannot trigger the param group's `post_backward` immediately after param usage;
|
| 378 |
+
# instead it relies on this to trigger the previously unexecuted `post_backward`.
|
| 379 |
+
self.post_backward()
|
| 380 |
+
if self._training_state == TrainingState.PRE_BACKWARD:
|
| 381 |
+
return
|
| 382 |
+
if not compiled_autograd_enabled():
|
| 383 |
+
logger.debug("%s", self._with_fqn("FSDP::pre_backward"))
|
| 384 |
+
with record_function(self._with_fqn("FSDP::pre_backward")):
|
| 385 |
+
self._training_state = TrainingState.PRE_BACKWARD
|
| 386 |
+
self.unshard(self.unshard_async_op) # no-op if prefetched
|
| 387 |
+
self.wait_for_unshard()
|
| 388 |
+
if default_prefetch and not compiled_autograd_enabled():
|
| 389 |
+
self._backward_prefetch()
|
| 390 |
+
|
| 391 |
+
def post_backward(self, *unused: Any):
|
| 392 |
+
# This method should be idempotent and safe to call even when this
|
| 393 |
+
# FSDP parameter group was not used in backward (should be a no-op)
|
| 394 |
+
if not compiled_autograd_enabled():
|
| 395 |
+
logger.debug("%s", self._with_fqn("FSDP::post_backward"))
|
| 396 |
+
self._training_state = TrainingState.POST_BACKWARD
|
| 397 |
+
with record_function(self._with_fqn("FSDP::post_backward_accumulate")):
|
| 398 |
+
for fsdp_param in self.fsdp_params:
|
| 399 |
+
fsdp_param.accumulate_unsharded_grad_if_needed()
|
| 400 |
+
with record_function(self._with_fqn("FSDP::post_backward_reshard")):
|
| 401 |
+
if not self.reduce_grads:
|
| 402 |
+
if self.reshard_after_backward:
|
| 403 |
+
self.reshard()
|
| 404 |
+
for fsdp_param in self.fsdp_params:
|
| 405 |
+
fsdp_param.to_accumulated_grad_if_needed()
|
| 406 |
+
return
|
| 407 |
+
# Save the autograd-computed gradients before resharding to only
|
| 408 |
+
# access the unsharded parameters when their data is present
|
| 409 |
+
fsdp_params_with_grad: list[FSDPParam] = []
|
| 410 |
+
unsharded_grads: list[torch.Tensor] = []
|
| 411 |
+
for fsdp_param in self.fsdp_params:
|
| 412 |
+
if not hasattr(fsdp_param, "_unsharded_param"):
|
| 413 |
+
continue
|
| 414 |
+
# May have an accumulated gradient of the reduce dtype if the
|
| 415 |
+
# previous backward did not reduce-scatter
|
| 416 |
+
if fsdp_param.unsharded_accumulated_grad is not None:
|
| 417 |
+
fsdp_params_with_grad.append(fsdp_param)
|
| 418 |
+
unsharded_grads.append(fsdp_param.unsharded_accumulated_grad_data)
|
| 419 |
+
fsdp_param.unsharded_accumulated_grad = None
|
| 420 |
+
elif fsdp_param.unsharded_param.grad is not None:
|
| 421 |
+
fsdp_params_with_grad.append(fsdp_param)
|
| 422 |
+
unsharded_grads.append(fsdp_param.unsharded_grad_data)
|
| 423 |
+
fsdp_param.unsharded_param.grad = None
|
| 424 |
+
if self.reshard_after_backward:
|
| 425 |
+
self.reshard()
|
| 426 |
+
if len(fsdp_params_with_grad) == 0:
|
| 427 |
+
return
|
| 428 |
+
with record_function(self._with_fqn("FSDP::post_backward_reduce")):
|
| 429 |
+
if (
|
| 430 |
+
self.comm_ctx.reduce_scatter_state is not None
|
| 431 |
+
and self.comm_ctx.reduce_scatter_state.event is not None
|
| 432 |
+
):
|
| 433 |
+
self.device_handle.current_stream().wait_event(
|
| 434 |
+
self.comm_ctx.reduce_scatter_state.event
|
| 435 |
+
)
|
| 436 |
+
self.comm_ctx.reduce_scatter_state = None
|
| 437 |
+
all_reduce_pg = self._all_reduce_process_group if self._is_hsdp else None
|
| 438 |
+
all_reduce_stream: torch.cuda.Stream
|
| 439 |
+
if all_reduce_pg is None and self._all_reduce_hook_stream is not None:
|
| 440 |
+
# this means the native HSDP is not enabled,
|
| 441 |
+
# but user may want to have a custom HSDP setup
|
| 442 |
+
assert self._all_reduce_hook is not None, (
|
| 443 |
+
"all reduce hook stream is specified but hook itself is missing."
|
| 444 |
+
)
|
| 445 |
+
all_reduce_stream = self._all_reduce_hook_stream
|
| 446 |
+
else:
|
| 447 |
+
all_reduce_stream = self.comm_ctx.all_reduce_stream
|
| 448 |
+
|
| 449 |
+
self._wait_for_post_backward()
|
| 450 |
+
(
|
| 451 |
+
reduce_scatter_input,
|
| 452 |
+
reduce_scatter_event,
|
| 453 |
+
self._post_reduce_event,
|
| 454 |
+
all_reduce_input,
|
| 455 |
+
all_reduce_event,
|
| 456 |
+
self._partial_reduce_output,
|
| 457 |
+
) = foreach_reduce(
|
| 458 |
+
fsdp_params_with_grad,
|
| 459 |
+
unsharded_grads,
|
| 460 |
+
self._reduce_scatter_process_group,
|
| 461 |
+
self.comm_ctx.reduce_scatter_stream,
|
| 462 |
+
self._orig_dtype,
|
| 463 |
+
self._reduce_dtype,
|
| 464 |
+
self.device,
|
| 465 |
+
self.gradient_divide_factor,
|
| 466 |
+
self._all_reduce_process_group if self._is_hsdp else None,
|
| 467 |
+
all_reduce_stream,
|
| 468 |
+
self.all_reduce_grads,
|
| 469 |
+
self._partial_reduce_output,
|
| 470 |
+
self._all_reduce_hook,
|
| 471 |
+
self.allocate_memory_from_process_group,
|
| 472 |
+
self.force_sum_reduction_for_comms,
|
| 473 |
+
)
|
| 474 |
+
self.comm_ctx.reduce_scatter_state = ReduceScatterState(
|
| 475 |
+
reduce_scatter_input, reduce_scatter_event
|
| 476 |
+
)
|
| 477 |
+
if all_reduce_input is not None:
|
| 478 |
+
if self.device.type != "cpu":
|
| 479 |
+
assert all_reduce_event is not None
|
| 480 |
+
self._all_reduce_state = AllReduceState(
|
| 481 |
+
all_reduce_input, all_reduce_event
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
def finalize_backward(self):
|
| 485 |
+
self._wait_for_post_backward()
|
| 486 |
+
for fsdp_param in self.fsdp_params:
|
| 487 |
+
if fsdp_param.grad_offload_event is not None:
|
| 488 |
+
fsdp_param.grad_offload_event.synchronize()
|
| 489 |
+
fsdp_param.grad_offload_event = None
|
| 490 |
+
if self._all_gather_result is not None:
|
| 491 |
+
# If there was a mistargeted unshard without a corresponding wait,
|
| 492 |
+
# then we wait here and clear the unshard
|
| 493 |
+
if (event := self._all_gather_result.all_gather_event) is not None:
|
| 494 |
+
torch.accelerator.current_stream().wait_event(event)
|
| 495 |
+
work = self._all_gather_result.all_gather_work
|
| 496 |
+
if isinstance(work, dist.distributed_c10d.Work):
|
| 497 |
+
work.wait()
|
| 498 |
+
self._all_gather_result = None
|
| 499 |
+
self._post_forward_indices.clear()
|
| 500 |
+
|
| 501 |
+
def _wait_for_post_backward(self):
|
| 502 |
+
if self._post_reduce_event is not None:
|
| 503 |
+
self.device_handle.current_stream().wait_event(self._post_reduce_event)
|
| 504 |
+
self._post_reduce_event = None
|
| 505 |
+
if (
|
| 506 |
+
self._all_reduce_state is not None
|
| 507 |
+
and self._all_reduce_state.event is not None
|
| 508 |
+
):
|
| 509 |
+
self.device_handle.current_stream().wait_event(self._all_reduce_state.event)
|
| 510 |
+
self._all_reduce_state = None
|
| 511 |
+
|
| 512 |
+
def _backward_prefetch(self) -> None:
|
| 513 |
+
if self._training_state == TrainingState.PRE_BACKWARD:
|
| 514 |
+
if not self._post_forward_indices:
|
| 515 |
+
# Can be cleared if running multiple `backward`s
|
| 516 |
+
return
|
| 517 |
+
curr_index = self._post_forward_indices.pop()
|
| 518 |
+
if (target_index := curr_index - 1) < 0:
|
| 519 |
+
return
|
| 520 |
+
# Prefetch naively using the reverse post-forward order, which may
|
| 521 |
+
# have mistargeted prefetches if not all modules used in forward
|
| 522 |
+
# are used in this backward
|
| 523 |
+
target_fsdp_param_group = self.comm_ctx.post_forward_order[target_index]
|
| 524 |
+
self._prefetch_unshard(target_fsdp_param_group, "backward")
|
| 525 |
+
|
| 526 |
+
@staticmethod
|
| 527 |
+
def _prefetch_unshard(
|
| 528 |
+
target_fsdp_param_group: "FSDPParamGroup", pass_type: str
|
| 529 |
+
) -> None:
|
| 530 |
+
if pass_type == "backward":
|
| 531 |
+
training_state = TrainingState.PRE_BACKWARD
|
| 532 |
+
elif pass_type == "forward":
|
| 533 |
+
training_state = TrainingState.FORWARD
|
| 534 |
+
else:
|
| 535 |
+
raise ValueError(f"Unknown pass type: {pass_type}")
|
| 536 |
+
target_fqn = target_fsdp_param_group._module_fqn
|
| 537 |
+
with (
|
| 538 |
+
record_function(f"FSDP::{pass_type}_prefetch for {target_fqn}"),
|
| 539 |
+
target_fsdp_param_group.use_training_state(training_state),
|
| 540 |
+
):
|
| 541 |
+
async_op = target_fsdp_param_group.unshard_async_op
|
| 542 |
+
target_fsdp_param_group.unshard(async_op)
|
| 543 |
+
|
| 544 |
+
# Utilities #
|
| 545 |
+
def _to_sharded(self):
|
| 546 |
+
if not self.is_sharded:
|
| 547 |
+
for fsdp_param in self.fsdp_params:
|
| 548 |
+
fsdp_param.to_sharded()
|
| 549 |
+
self._sharded_state = ShardedState.SHARDED
|
| 550 |
+
|
| 551 |
+
def _to_sharded_post_forward(self):
|
| 552 |
+
if not self.is_sharded_post_forward:
|
| 553 |
+
for fsdp_param in self.fsdp_params:
|
| 554 |
+
fsdp_param.to_sharded_post_forward()
|
| 555 |
+
self._sharded_state = ShardedState.SHARDED_POST_FORWARD
|
| 556 |
+
|
| 557 |
+
def _to_unsharded(self):
|
| 558 |
+
if not self.is_unsharded:
|
| 559 |
+
for fsdp_param in self.fsdp_params:
|
| 560 |
+
fsdp_param.to_unsharded()
|
| 561 |
+
self._sharded_state = ShardedState.UNSHARDED
|
| 562 |
+
|
| 563 |
+
@property
|
| 564 |
+
def is_sharded(self) -> bool:
|
| 565 |
+
return self._sharded_state == ShardedState.SHARDED
|
| 566 |
+
|
| 567 |
+
@property
|
| 568 |
+
def is_sharded_post_forward(self) -> bool:
|
| 569 |
+
return self._sharded_state == ShardedState.SHARDED_POST_FORWARD
|
| 570 |
+
|
| 571 |
+
@property
|
| 572 |
+
def is_unsharded(self) -> bool:
|
| 573 |
+
return self._sharded_state == ShardedState.UNSHARDED
|
| 574 |
+
|
| 575 |
+
@contextlib.contextmanager
|
| 576 |
+
def use_training_state(self, training_state: TrainingState):
|
| 577 |
+
old_training_state = self._training_state
|
| 578 |
+
self._training_state = training_state
|
| 579 |
+
try:
|
| 580 |
+
yield
|
| 581 |
+
finally:
|
| 582 |
+
self._training_state = old_training_state
|
| 583 |
+
|
| 584 |
+
# Hook Registration #
|
| 585 |
+
def _register_post_backward_hook(
|
| 586 |
+
self, args: tuple[Any, ...], kwargs: dict[str, Any]
|
| 587 |
+
) -> tuple[tuple[Any, ...], dict[str, Any]]:
|
| 588 |
+
# Traceable FSDP2 relies on `root_post_backward_callback` to call each
|
| 589 |
+
# `FSDPParamGroup.post_backward`
|
| 590 |
+
if (not torch._dynamo.config.skip_fsdp_hooks) or compiled_autograd_enabled():
|
| 591 |
+
return args, kwargs
|
| 592 |
+
if not torch.is_grad_enabled():
|
| 593 |
+
return args, kwargs
|
| 594 |
+
args_list, args_spec = tree_flatten(args)
|
| 595 |
+
kwargs_list, kwargs_spec = tree_flatten(kwargs)
|
| 596 |
+
args_kwargs_list = list(args_list) + list(kwargs_list)
|
| 597 |
+
inp_tensor_indices: list[int] = []
|
| 598 |
+
inp_tensors: list[torch.Tensor] = []
|
| 599 |
+
for i, obj in enumerate(args_kwargs_list):
|
| 600 |
+
if torch.is_tensor(obj) and obj.requires_grad:
|
| 601 |
+
inp_tensor_indices.append(i)
|
| 602 |
+
inp_tensors.append(obj)
|
| 603 |
+
if len(inp_tensors) == 0:
|
| 604 |
+
return args, kwargs # no tensors that require gradients
|
| 605 |
+
inp_tensors = RegisterPostBackwardFunction.apply(self, *inp_tensors)
|
| 606 |
+
for inp_tensor_idx, inp_tensor in zip(inp_tensor_indices, inp_tensors):
|
| 607 |
+
args_kwargs_list[inp_tensor_idx] = inp_tensor
|
| 608 |
+
args_list = args_kwargs_list[: len(args_list)]
|
| 609 |
+
kwargs_list = args_kwargs_list[len(args_list) :]
|
| 610 |
+
args = tree_unflatten(args_list, args_spec)
|
| 611 |
+
kwargs = tree_unflatten(kwargs_list, kwargs_spec)
|
| 612 |
+
return args, kwargs
|
| 613 |
+
|
| 614 |
+
def _register_state_dict_hooks(self) -> None:
|
| 615 |
+
num_pre_save_hooks = len(self._module_to_pre_save_state_dict_hook_handle)
|
| 616 |
+
num_pre_load_hooks = len(self._module_to_pre_load_state_dict_hook_handle)
|
| 617 |
+
assert num_pre_save_hooks == num_pre_load_hooks, (
|
| 618 |
+
f"Pre-save: {num_pre_save_hooks} pre-load: {num_pre_load_hooks}"
|
| 619 |
+
)
|
| 620 |
+
if num_pre_save_hooks > 0:
|
| 621 |
+
return # already registered
|
| 622 |
+
modules_with_fsdp_params: set[nn.Module] = {
|
| 623 |
+
fsdp_param._module_info.module for fsdp_param in self.fsdp_params
|
| 624 |
+
}
|
| 625 |
+
|
| 626 |
+
def to_sharded_hook(*args: Any, **kwargs: Any) -> None:
|
| 627 |
+
self._to_sharded()
|
| 628 |
+
|
| 629 |
+
for module in modules_with_fsdp_params:
|
| 630 |
+
self._module_to_pre_save_state_dict_hook_handle[module] = (
|
| 631 |
+
module.register_state_dict_pre_hook(to_sharded_hook)
|
| 632 |
+
)
|
| 633 |
+
self._module_to_pre_load_state_dict_hook_handle[module] = (
|
| 634 |
+
module._register_load_state_dict_pre_hook(to_sharded_hook)
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
# Properties #
|
| 638 |
+
@property
|
| 639 |
+
def _reshard_after_forward(self) -> bool:
|
| 640 |
+
return self.post_forward_mesh_info is not None
|
| 641 |
+
|
| 642 |
+
@property
|
| 643 |
+
def _use_post_forward_mesh(self) -> bool:
|
| 644 |
+
return (
|
| 645 |
+
self._reshard_after_forward
|
| 646 |
+
and self.mesh_info != self.post_forward_mesh_info
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
@property
|
| 650 |
+
def _is_hsdp(self) -> bool:
|
| 651 |
+
return isinstance(self.mesh_info, HSDPMeshInfo)
|
| 652 |
+
|
| 653 |
+
@property
|
| 654 |
+
def _all_gather_process_group(self) -> dist.ProcessGroup:
|
| 655 |
+
mesh_info = (
|
| 656 |
+
cast(FSDPMeshInfo, self.post_forward_mesh_info)
|
| 657 |
+
if self.is_sharded_post_forward
|
| 658 |
+
else self.mesh_info
|
| 659 |
+
)
|
| 660 |
+
assert isinstance(mesh_info, FSDPMeshInfo)
|
| 661 |
+
return mesh_info.shard_process_group
|
| 662 |
+
|
| 663 |
+
@property
|
| 664 |
+
def _reduce_scatter_process_group(self) -> dist.ProcessGroup:
|
| 665 |
+
assert isinstance(self.mesh_info, FSDPMeshInfo)
|
| 666 |
+
return self.mesh_info.shard_process_group
|
| 667 |
+
|
| 668 |
+
@property
|
| 669 |
+
def _all_reduce_process_group(self) -> dist.ProcessGroup:
|
| 670 |
+
assert isinstance(self.mesh_info, HSDPMeshInfo)
|
| 671 |
+
return self.mesh_info.replicate_process_group
|
| 672 |
+
|
| 673 |
+
def _with_fqn(self, label: str) -> str:
|
| 674 |
+
if self._module_fqn:
|
| 675 |
+
return f"{label} ({self._module_fqn})"
|
| 676 |
+
return label
|
| 677 |
+
|
| 678 |
+
def __repr__(self):
|
| 679 |
+
return f"FSDPParamGroup(fqn={self._module_fqn})"
|
| 680 |
+
|
| 681 |
+
def _validate_no_meta_params(self):
|
| 682 |
+
param_names_on_meta = [
|
| 683 |
+
fsdp_param._param_fqn
|
| 684 |
+
for fsdp_param in self.fsdp_params
|
| 685 |
+
if fsdp_param.sharded_param.device.type == "meta"
|
| 686 |
+
]
|
| 687 |
+
if param_names_on_meta:
|
| 688 |
+
raise RuntimeError(
|
| 689 |
+
"FSDP parameters should be materialized from meta device before training, "
|
| 690 |
+
f"but the following were still on meta device: {param_names_on_meta}\n"
|
| 691 |
+
"For example, call module.to_empty(device) to materialize to device and "
|
| 692 |
+
"call module.reset_parameters() on each module to initialize values."
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
def _validate_cpu_offload_params(self):
|
| 696 |
+
if not isinstance(self.offload_policy, CPUOffloadPolicy):
|
| 697 |
+
return
|
| 698 |
+
fsdp_params_not_on_cpu = [
|
| 699 |
+
fsdp_param
|
| 700 |
+
for fsdp_param in self.fsdp_params
|
| 701 |
+
if fsdp_param.sharded_param.device.type != "cpu"
|
| 702 |
+
]
|
| 703 |
+
if fsdp_params_not_on_cpu:
|
| 704 |
+
raise RuntimeError(
|
| 705 |
+
"FSDP parameters should be materialized on CPU when enabling CPU offloading. "
|
| 706 |
+
'For example, load a CPU state dict or call module.to_empty(device="cpu"). '
|
| 707 |
+
"Found following parameters on non-CPU device: "
|
| 708 |
+
f"{[(fsdp_param._param_fqn, fsdp_param.sharded_param.device) for fsdp_param in fsdp_params_not_on_cpu]}\n"
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
def _get_param_module_infos(
|
| 713 |
+
params: list[nn.Parameter], modules: tuple[nn.Module, ...]
|
| 714 |
+
) -> list[ParamModuleInfo]:
|
| 715 |
+
"""
|
| 716 |
+
Shared parameter: lin1.weight = lin2.weight
|
| 717 |
+
Shared module: mlp.lin1 = mlp.lin2
|
| 718 |
+
We do not remove duplicates when traversing both modules and parameters to
|
| 719 |
+
find shared modules' parameters and shared parameters within a module.
|
| 720 |
+
"""
|
| 721 |
+
params_set = set(params)
|
| 722 |
+
param_to_module_info: dict[nn.Parameter, ParamModuleInfo] = {}
|
| 723 |
+
for module in modules:
|
| 724 |
+
for _, submodule in module.named_modules(remove_duplicate=False):
|
| 725 |
+
for param_name, param in _named_parameters_with_duplicates(
|
| 726 |
+
submodule, recurse=False
|
| 727 |
+
):
|
| 728 |
+
if param in params_set:
|
| 729 |
+
if param not in param_to_module_info:
|
| 730 |
+
param_to_module_info[param] = ParamModuleInfo(
|
| 731 |
+
submodule, param_name
|
| 732 |
+
)
|
| 733 |
+
else:
|
| 734 |
+
param_to_module_info[param].shared_modules.append(submodule)
|
| 735 |
+
param_to_module_info[param].shared_param_names.append(
|
| 736 |
+
param_name
|
| 737 |
+
)
|
| 738 |
+
if len(param_to_module_info) != len(params):
|
| 739 |
+
raise AssertionError(f"Some parameters are not in the module tree of {module}")
|
| 740 |
+
return [param_to_module_info[param] for param in params]
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
class RegisterPostBackwardFunction(torch.autograd.Function):
|
| 744 |
+
@staticmethod
|
| 745 |
+
def _assert_not_tracing_fsdp():
|
| 746 |
+
if compiled_autograd_enabled():
|
| 747 |
+
# TODO: Find a way to print the offending FSDP2 module.
|
| 748 |
+
msg = """\
|
| 749 |
+
When Traceable FSDP2 is enabled, we should not be calling into `RegisterPostBackwardFunction`.
|
| 750 |
+
Instead, we rely on the param group's next `pre_backward` hook to trigger its previously unexecuted
|
| 751 |
+
`post_backward`, and we rely on FSDPState's `root_post_backward_callback` to trigger the resharding
|
| 752 |
+
of any leftover unsharded param groups.
|
| 753 |
+
If you are here, it means the forward part of this FSDP2 instance is not compiled, and you must also
|
| 754 |
+
compile the forward part if you want to use Traceable FSDP2."""
|
| 755 |
+
torch._dynamo.comptime.comptime.print(msg)
|
| 756 |
+
raise RuntimeError(msg)
|
| 757 |
+
|
| 758 |
+
@staticmethod
|
| 759 |
+
def forward(ctx, param_group: FSDPParamGroup, *inputs: torch.Tensor):
|
| 760 |
+
# All tensors in `inputs` should require gradient
|
| 761 |
+
RegisterPostBackwardFunction._assert_not_tracing_fsdp()
|
| 762 |
+
ctx.param_group = param_group
|
| 763 |
+
return inputs
|
| 764 |
+
|
| 765 |
+
@staticmethod
|
| 766 |
+
def backward(ctx, *grads: torch.Tensor):
|
| 767 |
+
RegisterPostBackw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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
import functools
|
| 4 |
+
import logging
|
| 5 |
+
from collections.abc import Sequence
|
| 6 |
+
from typing import Any, Callable, Optional, TYPE_CHECKING
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch._logging import warning_once
|
| 11 |
+
from torch.autograd import Variable
|
| 12 |
+
from torch.autograd.graph import _MultiHandle
|
| 13 |
+
from torch.distributed._composable_state import (
|
| 14 |
+
_get_module_state,
|
| 15 |
+
_insert_module_state,
|
| 16 |
+
_State,
|
| 17 |
+
)
|
| 18 |
+
from torch.distributed.device_mesh import _get_device_handle
|
| 19 |
+
from torch.distributed.utils import _apply_to_tensors, _to_kwargs
|
| 20 |
+
from torch.utils._pytree import tree_flatten
|
| 21 |
+
|
| 22 |
+
from ._fsdp_api import MixedPrecisionPolicy
|
| 23 |
+
from ._fsdp_common import (
|
| 24 |
+
_cast_fp_tensor,
|
| 25 |
+
compiled_autograd_enabled,
|
| 26 |
+
detect_compiled_autograd,
|
| 27 |
+
TrainingState,
|
| 28 |
+
)
|
| 29 |
+
from ._fsdp_param_group import FSDPCommContext, FSDPParamGroup
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
from ._fsdp_param import FSDPParam
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
logger = logging.getLogger("torch.distributed.fsdp.fully_shard")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class FSDPStateContext:
|
| 40 |
+
"""This has state shared across FSDP states."""
|
| 41 |
+
|
| 42 |
+
def __init__(self) -> None:
|
| 43 |
+
# All FSDP states in the root state's module tree
|
| 44 |
+
self.all_states: list[FSDPState] = []
|
| 45 |
+
# Iteration's forward root runs the once-per-forward logic; this root
|
| 46 |
+
# may not be the overall root set by lazy initialization in cases where
|
| 47 |
+
# only a submodule runs forward (e.g. encoder-only for eval)
|
| 48 |
+
self.iter_forward_root: Optional[FSDPState] = None
|
| 49 |
+
# Final callback should only be queued once per backward
|
| 50 |
+
self.post_backward_final_callback_queued: bool = False
|
| 51 |
+
# Whether to finalize backward in this backward's final callback
|
| 52 |
+
self.is_last_backward: bool = True
|
| 53 |
+
# Optional user-provided event recorded after optimizer for the
|
| 54 |
+
# all-gather streams to wait on in the root pre-forward
|
| 55 |
+
self.post_optim_event: Optional[torch.Event] = None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def disable_if_config_true(func):
|
| 59 |
+
@functools.wraps(func)
|
| 60 |
+
def fsdp_hook_wrapper(*args, **kwargs):
|
| 61 |
+
if torch._dynamo.config.skip_fsdp_hooks:
|
| 62 |
+
return torch._dynamo.disable(
|
| 63 |
+
func,
|
| 64 |
+
recursive=True,
|
| 65 |
+
reason="skipping FSDP hooks since torch._dynamo.config.skip_fsdp_hooks is set",
|
| 66 |
+
)(*args, **kwargs)
|
| 67 |
+
else:
|
| 68 |
+
return func(*args, **kwargs)
|
| 69 |
+
|
| 70 |
+
return fsdp_hook_wrapper
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class FSDPState(_State):
|
| 74 |
+
def __init__(self) -> None:
|
| 75 |
+
super().__init__()
|
| 76 |
+
self._fsdp_param_group: Optional[FSDPParamGroup] = None
|
| 77 |
+
self._is_root: Optional[bool] = None # root set during lazy init
|
| 78 |
+
self._state_ctx = FSDPStateContext()
|
| 79 |
+
self._comm_ctx = FSDPCommContext()
|
| 80 |
+
self._training_state: TrainingState = TrainingState.IDLE
|
| 81 |
+
self._states_to_forward_prefetch: list[FSDPState] = []
|
| 82 |
+
self._states_to_backward_prefetch: list[FSDPState] = []
|
| 83 |
+
self._modules_to_run_forward: set[nn.Module] = set()
|
| 84 |
+
# ``False`` when user set reshard_after_forward
|
| 85 |
+
# through ``fully_shard`` or ``set_reshard_after_forward``
|
| 86 |
+
self._auto_reshard_after_forward: Optional[bool] = True
|
| 87 |
+
|
| 88 |
+
# Define a separate init since `__init__` is called in the contract
|
| 89 |
+
def init(
|
| 90 |
+
self,
|
| 91 |
+
modules: tuple[nn.Module, ...],
|
| 92 |
+
device: torch.device,
|
| 93 |
+
mp_policy: MixedPrecisionPolicy,
|
| 94 |
+
auto_reshard_after_forward: bool,
|
| 95 |
+
) -> None:
|
| 96 |
+
for module in modules:
|
| 97 |
+
_insert_module_state(module, self)
|
| 98 |
+
self._modules = modules
|
| 99 |
+
self._device = device
|
| 100 |
+
self._device_handle = _get_device_handle(device.type)
|
| 101 |
+
self._mp_policy = mp_policy
|
| 102 |
+
self._auto_reshard_after_forward = auto_reshard_after_forward
|
| 103 |
+
if len(modules) == 1:
|
| 104 |
+
self._pre_forward_hook_handle = modules[0].register_forward_pre_hook(
|
| 105 |
+
self._pre_forward, prepend=True, with_kwargs=True
|
| 106 |
+
)
|
| 107 |
+
self._post_forward_hook_handle = modules[0].register_forward_hook(
|
| 108 |
+
self._post_forward, prepend=False
|
| 109 |
+
)
|
| 110 |
+
else:
|
| 111 |
+
hook_handle = _register_group_forward_hooks(
|
| 112 |
+
modules,
|
| 113 |
+
self._pre_forward,
|
| 114 |
+
self._post_forward,
|
| 115 |
+
self._modules_to_run_forward,
|
| 116 |
+
)
|
| 117 |
+
self._pre_forward_hook_handle = hook_handle
|
| 118 |
+
self._post_forward_hook_handle = hook_handle
|
| 119 |
+
|
| 120 |
+
def _root_pre_forward(
|
| 121 |
+
self, module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
|
| 122 |
+
) -> tuple[tuple[Any, ...], dict[str, Any]]:
|
| 123 |
+
self._lazy_init()
|
| 124 |
+
if self._state_ctx.iter_forward_root is not None:
|
| 125 |
+
return args, kwargs
|
| 126 |
+
if not compiled_autograd_enabled():
|
| 127 |
+
logger.debug("FSDP::root_pre_forward")
|
| 128 |
+
self._state_ctx.iter_forward_root = self
|
| 129 |
+
with torch.profiler.record_function("FSDP::root_pre_forward"):
|
| 130 |
+
# Wait for optimizer before implicitly prefetched all-gathers
|
| 131 |
+
if (event := self._state_ctx.post_optim_event) is not None:
|
| 132 |
+
self._comm_ctx.all_gather_copy_in_stream.wait_event(event)
|
| 133 |
+
self._comm_ctx.all_gather_stream.wait_event(event)
|
| 134 |
+
self._state_ctx.post_optim_event = None
|
| 135 |
+
else:
|
| 136 |
+
current_stream = self._device_handle.current_stream()
|
| 137 |
+
self._comm_ctx.all_gather_copy_in_stream.wait_stream(current_stream)
|
| 138 |
+
self._comm_ctx.all_gather_stream.wait_stream(current_stream)
|
| 139 |
+
if self._device.type in [
|
| 140 |
+
"cuda",
|
| 141 |
+
"hpu",
|
| 142 |
+
"xpu",
|
| 143 |
+
"mtia",
|
| 144 |
+
torch._C._get_privateuse1_backend_name(),
|
| 145 |
+
]:
|
| 146 |
+
with torch.profiler.record_function("FSDP::inputs_to_device"):
|
| 147 |
+
args_tuple, kwargs_tuple = _to_kwargs(
|
| 148 |
+
args, kwargs, self._device, False
|
| 149 |
+
) # same as DDP
|
| 150 |
+
args, kwargs = args_tuple[0], kwargs_tuple[0]
|
| 151 |
+
return args, kwargs
|
| 152 |
+
|
| 153 |
+
def _lazy_init(self) -> None:
|
| 154 |
+
"""
|
| 155 |
+
Lazy initialization represents when all modules' parallelisms have
|
| 156 |
+
finalized (e.g. FSDP has been applied to all desired modules). This
|
| 157 |
+
means that we can determine which state is the root, and we do so by
|
| 158 |
+
the 1st state to run forward.
|
| 159 |
+
"""
|
| 160 |
+
if self._is_root is not None:
|
| 161 |
+
return # no-op: already initialized
|
| 162 |
+
self._is_root = True
|
| 163 |
+
if len(self._modules) > 1:
|
| 164 |
+
raise RuntimeError(
|
| 165 |
+
f"FSDP requires a single root module but got {self._modules}"
|
| 166 |
+
)
|
| 167 |
+
detect_compiled_autograd()
|
| 168 |
+
root_module = self._modules[0]
|
| 169 |
+
visited_states: set[FSDPState] = set()
|
| 170 |
+
for module_name, module in root_module.named_modules():
|
| 171 |
+
if (state := _get_module_fsdp_state(module)) is None:
|
| 172 |
+
continue
|
| 173 |
+
if module is not root_module:
|
| 174 |
+
if state not in visited_states and state._is_root is not None:
|
| 175 |
+
raise RuntimeError(
|
| 176 |
+
"FSDP state has already been lazily initialized for "
|
| 177 |
+
f"{module_name}\nFSDP requires running forward through "
|
| 178 |
+
"the root module first"
|
| 179 |
+
)
|
| 180 |
+
state._is_root = False
|
| 181 |
+
self._state_ctx.all_states.append(state)
|
| 182 |
+
visited_states.add(state)
|
| 183 |
+
if self._fsdp_param_group and self._auto_reshard_after_forward:
|
| 184 |
+
# For the root, do not reshard after forward since for training,
|
| 185 |
+
# the parameters would be freed and all-gathered immediately
|
| 186 |
+
self._fsdp_param_group.post_forward_mesh_info = None
|
| 187 |
+
self._init_fqns()
|
| 188 |
+
self._init_shared_state()
|
| 189 |
+
# Run parameter group lazy inits after initializing FQNs for improved
|
| 190 |
+
# error messages
|
| 191 |
+
for state in self._state_ctx.all_states:
|
| 192 |
+
if state._fsdp_param_group:
|
| 193 |
+
state._fsdp_param_group.lazy_init()
|
| 194 |
+
|
| 195 |
+
def _init_shared_state(self) -> None:
|
| 196 |
+
self._comm_ctx.lazy_init(self._device)
|
| 197 |
+
for state in self._state_ctx.all_states:
|
| 198 |
+
state._state_ctx = self._state_ctx
|
| 199 |
+
state._comm_ctx = self._comm_ctx
|
| 200 |
+
if fsdp_param_group := state._fsdp_param_group:
|
| 201 |
+
fsdp_param_group.comm_ctx = self._comm_ctx
|
| 202 |
+
|
| 203 |
+
def _init_fqns(self) -> None:
|
| 204 |
+
"""Sets module and parameter FQN attributes for debugging."""
|
| 205 |
+
assert self._is_root
|
| 206 |
+
root_module = self._modules[0]
|
| 207 |
+
param_to_fsdp_param: dict[nn.Parameter, FSDPParam] = {}
|
| 208 |
+
module_to_fsdp_param_group: dict[nn.Module, FSDPParamGroup] = {}
|
| 209 |
+
for state in self._state_ctx.all_states:
|
| 210 |
+
if fsdp_param_group := state._fsdp_param_group:
|
| 211 |
+
for fsdp_param in fsdp_param_group.fsdp_params:
|
| 212 |
+
param_to_fsdp_param[fsdp_param.sharded_param] = fsdp_param
|
| 213 |
+
for module in fsdp_param_group.modules:
|
| 214 |
+
module_to_fsdp_param_group[module] = fsdp_param_group
|
| 215 |
+
for param_name, param in root_module.named_parameters():
|
| 216 |
+
if param in param_to_fsdp_param:
|
| 217 |
+
param_to_fsdp_param[param]._param_fqn = param_name
|
| 218 |
+
for module_name, module in root_module.named_modules():
|
| 219 |
+
if module in module_to_fsdp_param_group:
|
| 220 |
+
module_fqn = module_to_fsdp_param_group[module]._module_fqn
|
| 221 |
+
if module_fqn is None:
|
| 222 |
+
module_to_fsdp_param_group[module]._module_fqn = module_name
|
| 223 |
+
else:
|
| 224 |
+
assert isinstance(module_fqn, str), f"{module_fqn}"
|
| 225 |
+
module_fqn += f", {module_name}"
|
| 226 |
+
module_to_fsdp_param_group[module]._module_fqn = module_fqn
|
| 227 |
+
|
| 228 |
+
@disable_if_config_true
|
| 229 |
+
def _pre_forward(
|
| 230 |
+
self, module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
|
| 231 |
+
) -> tuple[tuple[Any, ...], dict[str, Any]]:
|
| 232 |
+
# When composing with module-hook-based activation checkpointing, the
|
| 233 |
+
# the pre-backward hook is responsible for the unshard
|
| 234 |
+
if self._training_state == TrainingState.PRE_BACKWARD:
|
| 235 |
+
return args, kwargs
|
| 236 |
+
self._training_state = TrainingState.FORWARD
|
| 237 |
+
args, kwargs = self._root_pre_forward(module, args, kwargs)
|
| 238 |
+
if self._mp_policy.cast_forward_inputs and self._mp_policy.param_dtype:
|
| 239 |
+
with torch.profiler.record_function("FSDP::cast_forward_inputs"):
|
| 240 |
+
cast_fn = functools.partial(
|
| 241 |
+
_cast_fp_tensor, self._mp_policy.param_dtype
|
| 242 |
+
)
|
| 243 |
+
args, kwargs = (
|
| 244 |
+
_apply_to_tensors(cast_fn, args),
|
| 245 |
+
_apply_to_tensors(cast_fn, kwargs),
|
| 246 |
+
)
|
| 247 |
+
if self._fsdp_param_group:
|
| 248 |
+
args, kwargs = self._fsdp_param_group.pre_forward(module, args, kwargs)
|
| 249 |
+
for fsdp_state in self._states_to_forward_prefetch:
|
| 250 |
+
if (target_param_group := fsdp_state._fsdp_param_group) is not None:
|
| 251 |
+
FSDPParamGroup._prefetch_unshard(target_param_group, "forward")
|
| 252 |
+
return args, kwargs
|
| 253 |
+
|
| 254 |
+
@disable_if_config_true
|
| 255 |
+
def _post_forward(self, module: nn.Module, input: Any, output: Any) -> Any:
|
| 256 |
+
# When composing with module-hook-based activation checkpointing, the
|
| 257 |
+
# post-backward hook is responsible for the reshard
|
| 258 |
+
if self._training_state == TrainingState.PRE_BACKWARD:
|
| 259 |
+
return output
|
| 260 |
+
if self._fsdp_param_group:
|
| 261 |
+
output = self._fsdp_param_group.post_forward(module, input, output)
|
| 262 |
+
output = self._register_pre_backward_hook(output)
|
| 263 |
+
self._training_state = TrainingState.IDLE
|
| 264 |
+
if self._state_ctx.iter_forward_root is self:
|
| 265 |
+
if all_gather_state := self._comm_ctx.all_gather_state:
|
| 266 |
+
# Free the last all-gather result if needed; refer to
|
| 267 |
+
# [Note: Overlapping all-gather copy-in and all-gather]
|
| 268 |
+
self._comm_ctx.all_gather_copy_in_stream.wait_event(
|
| 269 |
+
all_gather_state.event
|
| 270 |
+
)
|
| 271 |
+
self._comm_ctx.all_gather_stream.wait_event(all_gather_state.event)
|
| 272 |
+
self._comm_ctx.all_gather_state = None # free the all-gather result
|
| 273 |
+
self._state_ctx.iter_forward_root = None
|
| 274 |
+
if self._mp_policy.output_dtype is not None:
|
| 275 |
+
with torch.profiler.record_function("FSDP::cast_forward_outputs"):
|
| 276 |
+
output = _apply_to_tensors(
|
| 277 |
+
functools.partial(_cast_fp_tensor, self._mp_policy.output_dtype),
|
| 278 |
+
output,
|
| 279 |
+
)
|
| 280 |
+
return output
|
| 281 |
+
|
| 282 |
+
def _pre_backward(self, grad: torch.Tensor) -> torch.Tensor:
|
| 283 |
+
self._training_state = TrainingState.PRE_BACKWARD
|
| 284 |
+
self._register_root_post_backward_final_callback()
|
| 285 |
+
if self._fsdp_param_group:
|
| 286 |
+
default_prefetch = len(self._states_to_backward_prefetch) == 0
|
| 287 |
+
self._fsdp_param_group.pre_backward(default_prefetch)
|
| 288 |
+
for fsdp_state in self._states_to_backward_prefetch:
|
| 289 |
+
if (target_param_group := fsdp_state._fsdp_param_group) is not None:
|
| 290 |
+
FSDPParamGroup._prefetch_unshard(target_param_group, "backward")
|
| 291 |
+
return grad
|
| 292 |
+
|
| 293 |
+
def _root_post_backward_final_callback(self) -> None:
|
| 294 |
+
if not compiled_autograd_enabled():
|
| 295 |
+
logger.debug("FSDP::root_post_backward")
|
| 296 |
+
with torch.profiler.record_function("FSDP::root_post_backward_callback"):
|
| 297 |
+
for state in self._state_ctx.all_states:
|
| 298 |
+
fsdp_param_group = state._fsdp_param_group
|
| 299 |
+
if (
|
| 300 |
+
fsdp_param_group
|
| 301 |
+
and fsdp_param_group._training_state != TrainingState.POST_BACKWARD
|
| 302 |
+
):
|
| 303 |
+
# Run post-backward in case forward inputs did not require
|
| 304 |
+
# gradient so the autograd backward did not run
|
| 305 |
+
fsdp_param_group.post_backward()
|
| 306 |
+
state._training_state = TrainingState.IDLE
|
| 307 |
+
if fsdp_param_group:
|
| 308 |
+
fsdp_param_group._training_state = TrainingState.IDLE
|
| 309 |
+
if self._state_ctx.is_last_backward:
|
| 310 |
+
state._finalize_backward()
|
| 311 |
+
if self._state_ctx.is_last_backward:
|
| 312 |
+
self._comm_ctx.post_forward_order.clear()
|
| 313 |
+
if self._comm_ctx.reduce_scatter_state is not None:
|
| 314 |
+
self._device_handle.current_stream().wait_event(
|
| 315 |
+
self._comm_ctx.reduce_scatter_state.event
|
| 316 |
+
)
|
| 317 |
+
self._comm_ctx.reduce_scatter_state = None
|
| 318 |
+
self._state_ctx.post_backward_final_callback_queued = False
|
| 319 |
+
|
| 320 |
+
def _finalize_backward(self) -> None:
|
| 321 |
+
if self._modules_to_run_forward:
|
| 322 |
+
msg = (
|
| 323 |
+
f"{len(self._modules_to_run_forward)} of the {len(self._modules)} "
|
| 324 |
+
f"modules passed to fully_shard did not run forward before backward, "
|
| 325 |
+
"which is error-prone since FSDP post-forward/pre-backward logic "
|
| 326 |
+
"will not run for these modules. We recommend passing only modules "
|
| 327 |
+
"that run forward together. Modules that did not run forward: "
|
| 328 |
+
f"{list(self._modules_to_run_forward)}"
|
| 329 |
+
)
|
| 330 |
+
warning_once(logger, msg, stacklevel=2)
|
| 331 |
+
# Clear since we want the next forward to run
|
| 332 |
+
self._modules_to_run_forward.clear()
|
| 333 |
+
if self._fsdp_param_group:
|
| 334 |
+
self._fsdp_param_group.finalize_backward()
|
| 335 |
+
|
| 336 |
+
def _register_pre_backward_hook(self, output: Any) -> Any:
|
| 337 |
+
if not torch.is_grad_enabled():
|
| 338 |
+
return output
|
| 339 |
+
flat_outputs, _ = tree_flatten(output)
|
| 340 |
+
for t in flat_outputs:
|
| 341 |
+
if torch.is_tensor(t) and t.requires_grad:
|
| 342 |
+
t.register_hook(self._pre_backward)
|
| 343 |
+
return output
|
| 344 |
+
|
| 345 |
+
def _register_root_post_backward_final_callback(self):
|
| 346 |
+
if self._state_ctx.post_backward_final_callback_queued:
|
| 347 |
+
return
|
| 348 |
+
self._state_ctx.post_backward_final_callback_queued = True
|
| 349 |
+
Variable._execution_engine.queue_callback(
|
| 350 |
+
self._root_post_backward_final_callback
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _get_module_fsdp_state(module: nn.Module) -> Optional[FSDPState]:
|
| 355 |
+
state = _get_module_state(module)
|
| 356 |
+
if isinstance(state, FSDPState):
|
| 357 |
+
return state
|
| 358 |
+
return None
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _register_group_forward_hooks(
|
| 362 |
+
modules: Sequence[nn.Module],
|
| 363 |
+
pre_hook: Callable,
|
| 364 |
+
post_hook: Callable,
|
| 365 |
+
modules_to_run: set[nn.Module],
|
| 366 |
+
):
|
| 367 |
+
"""
|
| 368 |
+
Registers group forward pre and post-hooks. The pre-hook runs upon the
|
| 369 |
+
first module pre-forward, and the post-hook runs upon the last. If at least
|
| 370 |
+
one module does not run forward, then the post-hook does not run.
|
| 371 |
+
"""
|
| 372 |
+
modules_set = set(modules)
|
| 373 |
+
|
| 374 |
+
@disable_if_config_true
|
| 375 |
+
@functools.wraps(pre_hook)
|
| 376 |
+
def wrapped_pre_hook(*args: Any, **kwargs: Any):
|
| 377 |
+
if len(modules_to_run) == 0: # first to run
|
| 378 |
+
modules_to_run.update(modules_set)
|
| 379 |
+
return pre_hook(*args, **kwargs)
|
| 380 |
+
|
| 381 |
+
@disable_if_config_true
|
| 382 |
+
def get_wrapped_post_hook(module: nn.Module):
|
| 383 |
+
@functools.wraps(post_hook)
|
| 384 |
+
def wrapped_post_hook(*args: Any, **kwargs: Any):
|
| 385 |
+
modules_to_run.discard(module)
|
| 386 |
+
if len(modules_to_run) == 0:
|
| 387 |
+
return post_hook(*args, **kwargs)
|
| 388 |
+
|
| 389 |
+
return wrapped_post_hook
|
| 390 |
+
|
| 391 |
+
pre_handles = [
|
| 392 |
+
module.register_forward_pre_hook(
|
| 393 |
+
wrapped_pre_hook, prepend=True, with_kwargs=True
|
| 394 |
+
)
|
| 395 |
+
for module in modules
|
| 396 |
+
]
|
| 397 |
+
post_handles = [
|
| 398 |
+
module.register_forward_hook(
|
| 399 |
+
get_wrapped_post_hook(module), prepend=False, always_call=True
|
| 400 |
+
)
|
| 401 |
+
for module in modules
|
| 402 |
+
]
|
| 403 |
+
return _MultiHandle(tuple(pre_handles + post_handles))
|
_fully_shard.py
ADDED
|
@@ -0,0 +1,672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import functools
|
| 7 |
+
from typing import (
|
| 8 |
+
Any,
|
| 9 |
+
Callable,
|
| 10 |
+
cast,
|
| 11 |
+
NoReturn,
|
| 12 |
+
Optional,
|
| 13 |
+
overload,
|
| 14 |
+
TYPE_CHECKING,
|
| 15 |
+
Union,
|
| 16 |
+
)
|
| 17 |
+
from typing_extensions import deprecated
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
from torch.distributed._composable import contract
|
| 22 |
+
from torch.distributed.utils import _get_root_modules
|
| 23 |
+
|
| 24 |
+
from ._fsdp_api import MixedPrecisionPolicy, OffloadPolicy
|
| 25 |
+
from ._fsdp_common import FSDPMeshInfo, HSDPMeshInfo
|
| 26 |
+
from ._fsdp_init import (
|
| 27 |
+
_get_device_from_mesh,
|
| 28 |
+
_get_managed_modules,
|
| 29 |
+
_get_managed_states,
|
| 30 |
+
_get_post_forward_mesh_info,
|
| 31 |
+
_init_default_fully_shard_mesh,
|
| 32 |
+
_move_states_to_device,
|
| 33 |
+
)
|
| 34 |
+
from ._fsdp_param_group import FSDPParamGroup
|
| 35 |
+
from ._fsdp_state import _get_module_fsdp_state, FSDPState
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if TYPE_CHECKING:
|
| 39 |
+
from collections.abc import Iterable
|
| 40 |
+
|
| 41 |
+
from torch.distributed.tensor import DeviceMesh, Shard
|
| 42 |
+
|
| 43 |
+
__all__ = [
|
| 44 |
+
"fully_shard",
|
| 45 |
+
"FSDPModule",
|
| 46 |
+
"UnshardHandle",
|
| 47 |
+
"register_fsdp_forward_method",
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
cls_to_fsdp_cls: dict[type, type] = {}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@overload
|
| 55 |
+
def fully_shard(
|
| 56 |
+
module: nn.Module,
|
| 57 |
+
*,
|
| 58 |
+
mesh: Optional[DeviceMesh] = ...,
|
| 59 |
+
reshard_after_forward: Union[bool, int] = ...,
|
| 60 |
+
shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]] = ...,
|
| 61 |
+
mp_policy: MixedPrecisionPolicy = ...,
|
| 62 |
+
offload_policy: OffloadPolicy = ...,
|
| 63 |
+
ignored_params: Optional[set[nn.Parameter]] = ...,
|
| 64 |
+
) -> FSDPModule: ...
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@overload
|
| 68 |
+
def fully_shard(
|
| 69 |
+
module: list[nn.Module],
|
| 70 |
+
*,
|
| 71 |
+
mesh: Optional[DeviceMesh] = ...,
|
| 72 |
+
reshard_after_forward: Union[bool, int] = ...,
|
| 73 |
+
shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]] = ...,
|
| 74 |
+
mp_policy: MixedPrecisionPolicy = ...,
|
| 75 |
+
offload_policy: OffloadPolicy = ...,
|
| 76 |
+
ignored_params: Optional[set[nn.Parameter]] = ...,
|
| 77 |
+
) -> list[FSDPModule]: ...
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# The decorator adds a state object to `module` that can be accessed via
|
| 81 |
+
# `fully_shard.state(module)`. The state object and module are 1:1.
|
| 82 |
+
# [1] Python runtime decorator does not play well with static type checking
|
| 83 |
+
# so suppressing some type checks to support type overloads
|
| 84 |
+
# such that caller can still get correct return types based on input type
|
| 85 |
+
@contract(state_cls=FSDPState) # type: ignore[misc] # see [1]
|
| 86 |
+
def fully_shard(
|
| 87 |
+
module,
|
| 88 |
+
*,
|
| 89 |
+
mesh: Optional[DeviceMesh] = None,
|
| 90 |
+
reshard_after_forward: Optional[Union[bool, int]] = None,
|
| 91 |
+
shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]] = None,
|
| 92 |
+
mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(),
|
| 93 |
+
offload_policy: OffloadPolicy = OffloadPolicy(),
|
| 94 |
+
ignored_params: Optional[set[nn.Parameter]] = None,
|
| 95 |
+
):
|
| 96 |
+
"""
|
| 97 |
+
Apply fully sharded data parallelism (FSDP) to ``module``, where FSDP
|
| 98 |
+
shards module parameters, gradients, and optimizer states across data
|
| 99 |
+
parallel workers to save memory at the cost of communication.
|
| 100 |
+
|
| 101 |
+
At initialization, FSDP shards the module's parameters across the data
|
| 102 |
+
parallel workers given by ``mesh``. Before forward, FSDP all-gathers the
|
| 103 |
+
sharded parameters across the data-parallel workers to get the unsharded
|
| 104 |
+
parameters for forward computation. If ``reshard_after_forward`` is
|
| 105 |
+
``True``, then FSDP frees the unsharded parameters after forward and
|
| 106 |
+
re-all-gathers them in backward before gradient computation. After gradient
|
| 107 |
+
computation, FSDP frees the unsharded parameters and reduce-scatters the
|
| 108 |
+
unsharded gradients across data-parallel workers.
|
| 109 |
+
|
| 110 |
+
This implementation represents the sharded parameters as :class:`DTensor` s
|
| 111 |
+
sharded on dim-0, while the unsharded parameters will be like the original
|
| 112 |
+
parameters on ``module`` (e.g. :class:`torch.Tensor` if originally
|
| 113 |
+
:class:`torch.Tensor`). A module
|
| 114 |
+
`forward pre-hook <https://pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.register_forward_pre_hook>`_
|
| 115 |
+
on ``module`` all-gathers the parameters, and a module
|
| 116 |
+
`forward hook <https://pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.register_forward_hook>`_
|
| 117 |
+
on ``module`` frees them (if needed). Similar backward hooks all-gather
|
| 118 |
+
parameters and later free parameters and reduce-scatter gradients.
|
| 119 |
+
|
| 120 |
+
Since grouping multiple tensors together for one collective is critical for
|
| 121 |
+
communication efficiency, this implementation makes this grouping first
|
| 122 |
+
class. Calling :meth:`fully_shard` on ``module`` constructs one group that
|
| 123 |
+
includes the parameters in ``module.parameters()`` except those already
|
| 124 |
+
assigned to a group from an earlier call on a submodule. This means that
|
| 125 |
+
:meth:`fully_shard` should be called bottom-up on your model. Each group's
|
| 126 |
+
parameters are all-gathered in one collective, and its gradients are
|
| 127 |
+
reduce-scattered in one collective. Partitioning the model into multiple
|
| 128 |
+
groups ("layer by layer") allows for peak memory savings and communication/computation
|
| 129 |
+
overlap. Users generally should *not* call :meth:`fully_shard` only on the
|
| 130 |
+
topmost root module.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
module (Union[nn.Module, List[nn.Module]): The module or modules to
|
| 134 |
+
shard with FSDP and group together for communication.
|
| 135 |
+
mesh (Optional[DeviceMesh]): This data parallel mesh defines the
|
| 136 |
+
sharding and device. If 1D, then parameters are fully sharded
|
| 137 |
+
across the 1D mesh (FSDP) with ``(Shard(0),)`` placement. If 2D,
|
| 138 |
+
then parameters are sharded across the 1st dim and replicated
|
| 139 |
+
across the 0th dim (HSDP) with ``(Replicate(), Shard(0))``
|
| 140 |
+
placement. The mesh's device type gives the device type used for
|
| 141 |
+
communication; if a CUDA or CUDA-like device type, then we use the
|
| 142 |
+
current device.
|
| 143 |
+
reshard_after_forward (Optional[Union[bool, int]]): This controls the parameter
|
| 144 |
+
behavior after forward and can trade off memory and communication:
|
| 145 |
+
|
| 146 |
+
- If ``True``, then this reshards parameters after forward and
|
| 147 |
+
re-all-gathers in backward.
|
| 148 |
+
- If ``False``, then this keeps the unsharded parameters in memory
|
| 149 |
+
after forward and avoids the all-gather in backward. For best performance,
|
| 150 |
+
we usually set ``False`` for the root module, because the root module
|
| 151 |
+
is typically required immediately when the backward pass begins.
|
| 152 |
+
- If ``None``, it is set to ``True`` for non-root modules and ``False``
|
| 153 |
+
for root modules.
|
| 154 |
+
- If an ``int``, then this represents the world size to reshard to
|
| 155 |
+
after forward. It should be a non-trivial divisor of the ``mesh``
|
| 156 |
+
shard dim size (i.e. excluding 1 and the dim size itself). A
|
| 157 |
+
choice may be the intra-node size (e.g. ``torch.cuda.device_count()``).
|
| 158 |
+
This allows the all-gather in backward to be over a smaller world
|
| 159 |
+
size at the cost of higher memory usage than setting to ``True``.
|
| 160 |
+
- After forward, the parameters registered to the module depend on
|
| 161 |
+
to this: The registered parameters are the sharded parameters if
|
| 162 |
+
``True``; unsharded parameters if ``False``; and the parameters
|
| 163 |
+
resharded to the smaller mesh otherwise. To modify the parameters
|
| 164 |
+
between forward and backward, the registered parameters must be
|
| 165 |
+
the sharded parameters. For ``False`` or an ``int``, this can be
|
| 166 |
+
done by manually resharding via :meth:`reshard`.
|
| 167 |
+
shard_placement_fn (Optional[Callable[[nn.Parameter], Optional[Shard]]]):
|
| 168 |
+
This callable can be used to override the sharding placement for a
|
| 169 |
+
parameter to shard a parameter on a dimension other than dim-0. If
|
| 170 |
+
this callable returns a :class:`Shard` placement (not ``None``),
|
| 171 |
+
then FSDP will shard according to that placement (e.g. ``Shard(1)``).
|
| 172 |
+
If sharding on a nonzero dim, we currently require even sharding,
|
| 173 |
+
i.e. the tensor dim size on that dim must be divisible by the FSDP
|
| 174 |
+
shard mesh size.
|
| 175 |
+
mp_policy (MixedPrecisionPolicy): This controls the mixed precision
|
| 176 |
+
policy, which offers parameter/reduction mixed precision for this
|
| 177 |
+
module. See :class:`MixedPrecisionPolicy` for details.
|
| 178 |
+
offload_policy (OffloadPolicy): This controls the offloading policy,
|
| 179 |
+
which offers parameter/gradient/optimizer state offloading. See
|
| 180 |
+
:class:`OffloadPolicy` and its subclasses for details.
|
| 181 |
+
ignored_params: Optional(Set[nn.Parameter]): The set of parameters to be
|
| 182 |
+
ignored by FSDP. They will not be sharded, nor moved to the device
|
| 183 |
+
during init, nor have their gradients reduced in backward.
|
| 184 |
+
|
| 185 |
+
Returns:
|
| 186 |
+
FSDPModule: The module with FSDP applied (in-place).
|
| 187 |
+
"""
|
| 188 |
+
torch._C._log_api_usage_once("torch.distributed.fsdp.fully_shard")
|
| 189 |
+
if isinstance(module, (nn.ModuleList, nn.ModuleDict)):
|
| 190 |
+
raise ValueError(
|
| 191 |
+
f"fully_shard does not support containers that do not implement forward: {module}"
|
| 192 |
+
)
|
| 193 |
+
mesh = mesh or _init_default_fully_shard_mesh()
|
| 194 |
+
if mesh.ndim not in (1, 2):
|
| 195 |
+
raise ValueError(f"fully_shard expects a 1D or 2D DeviceMesh but got {mesh}")
|
| 196 |
+
elif mesh.ndim == 1:
|
| 197 |
+
mesh_info = FSDPMeshInfo(mesh, shard_mesh_dim=0)
|
| 198 |
+
else:
|
| 199 |
+
if mesh.mesh_dim_names is None:
|
| 200 |
+
raise AssertionError(
|
| 201 |
+
"Please init the 2D mesh for HSDP with mesh_dim_names specified"
|
| 202 |
+
)
|
| 203 |
+
mesh_info = HSDPMeshInfo(mesh, shard_mesh_dim=1, replicate_mesh_dim=0)
|
| 204 |
+
device = _get_device_from_mesh(mesh)
|
| 205 |
+
auto_reshard_after_forward = reshard_after_forward is None
|
| 206 |
+
# If the user does not provide ``reshard_after_forward``, we set it to True.
|
| 207 |
+
# During lazy_init, we identify which module is the root and override its value to False
|
| 208 |
+
post_forward_mesh_info = _get_post_forward_mesh_info(
|
| 209 |
+
reshard_after_forward if not auto_reshard_after_forward else True, # type: ignore[arg-type]
|
| 210 |
+
mesh_info,
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
arg_module = module
|
| 214 |
+
modules = (
|
| 215 |
+
(module,) if isinstance(module, nn.Module) else tuple(_get_root_modules(module))
|
| 216 |
+
)
|
| 217 |
+
state = fully_shard.state(modules[0]) # type: ignore[attr-defined] # see [1]
|
| 218 |
+
state.init(modules, device, mp_policy, auto_reshard_after_forward)
|
| 219 |
+
|
| 220 |
+
managed_modules = _get_managed_modules(modules, ignored_params)
|
| 221 |
+
params, buffers = _get_managed_states(managed_modules, ignored_params)
|
| 222 |
+
|
| 223 |
+
_move_states_to_device(params, buffers, device)
|
| 224 |
+
if params:
|
| 225 |
+
state._fsdp_param_group = FSDPParamGroup(
|
| 226 |
+
params,
|
| 227 |
+
modules,
|
| 228 |
+
mesh_info,
|
| 229 |
+
post_forward_mesh_info,
|
| 230 |
+
device,
|
| 231 |
+
shard_placement_fn,
|
| 232 |
+
mp_policy,
|
| 233 |
+
offload_policy,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
# For Dynamo
|
| 237 |
+
for managed_module in managed_modules:
|
| 238 |
+
managed_module._is_fsdp_managed_module = True # type: ignore[assignment]
|
| 239 |
+
managed_module._fsdp_use_orig_params = True # type: ignore[assignment]
|
| 240 |
+
|
| 241 |
+
# Place FSDP leftmost for highest priority in the method resolution order
|
| 242 |
+
for module in modules:
|
| 243 |
+
cls = module.__class__
|
| 244 |
+
new_cls = cls_to_fsdp_cls.get(cls, None)
|
| 245 |
+
if not new_cls:
|
| 246 |
+
dct = {"__deepcopy__": _unimplemented_deepcopy}
|
| 247 |
+
new_cls = type(f"FSDP{cls.__name__}", (FSDPModule, cls), dct)
|
| 248 |
+
cls_to_fsdp_cls[cls] = new_cls
|
| 249 |
+
module.__class__ = new_cls
|
| 250 |
+
return arg_module
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _unimplemented_deepcopy(*args: Any, **kwargs: Any) -> NoReturn:
|
| 254 |
+
raise AssertionError(
|
| 255 |
+
"FSDP does not support deepcopy. Please use state dict for serialization."
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class FSDPModule:
|
| 260 |
+
def __new__(cls, *args, **kwargs):
|
| 261 |
+
"""
|
| 262 |
+
Override ``__new__`` to remove the FSDP class and directly construct
|
| 263 |
+
the original class for cases like indexing into a container module.
|
| 264 |
+
"""
|
| 265 |
+
# Use index 2 since 0 is the dynamically constructed `FSDP<...>` class
|
| 266 |
+
# and index 1 is the `FSDPModule` class itself
|
| 267 |
+
orig_cls = cls.__mro__[2]
|
| 268 |
+
self = orig_cls.__new__(orig_cls, *args, **kwargs)
|
| 269 |
+
self.__init__(*args, **kwargs)
|
| 270 |
+
return self
|
| 271 |
+
|
| 272 |
+
def reshard(self) -> None:
|
| 273 |
+
"""
|
| 274 |
+
Reshards the module's parameters, freeing the unsharded parameters if
|
| 275 |
+
they are allocated and registering the sharded parameters to the
|
| 276 |
+
module. This method is *not* recursive.
|
| 277 |
+
"""
|
| 278 |
+
state = self._get_fsdp_state()
|
| 279 |
+
if fsdp_param_group := state._fsdp_param_group:
|
| 280 |
+
fsdp_param_group.reshard()
|
| 281 |
+
|
| 282 |
+
def unshard(self, async_op: bool = False) -> Optional[UnshardHandle]:
|
| 283 |
+
"""
|
| 284 |
+
Unshards the module's parameters by allocating memory and all-gathering
|
| 285 |
+
the parameters. This method is *not* recursive. The unshard follows the
|
| 286 |
+
:class:`MixedPrecisionPolicy`, so it will all-gather following
|
| 287 |
+
``param_dtype`` if set.
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
async_op (bool): If ``True``, then returns a :class:`UnshardHandle`
|
| 291 |
+
that has a :meth:`wait` method to wait on the unshard op. If
|
| 292 |
+
``False``, then returns ``None`` and waits on the handle inside
|
| 293 |
+
this function.
|
| 294 |
+
|
| 295 |
+
.. note:: If ``async_op=True``, then FSDP will wait on the pending
|
| 296 |
+
unshard in the module's pre-forward for the user. The user only
|
| 297 |
+
needs to call :meth:`wait` explicitly if the wait should happen
|
| 298 |
+
before pre-forward.
|
| 299 |
+
"""
|
| 300 |
+
state = self._get_fsdp_state()
|
| 301 |
+
fsdp_param_group = state._fsdp_param_group
|
| 302 |
+
if fsdp_param_group is not None:
|
| 303 |
+
fsdp_param_group.lazy_init()
|
| 304 |
+
fsdp_param_group.unshard(async_op=async_op)
|
| 305 |
+
handle = _UnshardHandleImpl(fsdp_param_group)
|
| 306 |
+
if async_op:
|
| 307 |
+
return handle
|
| 308 |
+
handle.wait()
|
| 309 |
+
return None
|
| 310 |
+
|
| 311 |
+
def set_is_last_backward(self, is_last_backward: bool) -> None:
|
| 312 |
+
"""
|
| 313 |
+
Sets whether the next backward is the last one. On the last backward,
|
| 314 |
+
FSDP waits on pending gradient reduction and clears internal data
|
| 315 |
+
data structures for backward prefetching. This can be useful for
|
| 316 |
+
microbatching.
|
| 317 |
+
"""
|
| 318 |
+
state = self._get_fsdp_state()
|
| 319 |
+
state._state_ctx.is_last_backward = is_last_backward
|
| 320 |
+
|
| 321 |
+
def set_requires_gradient_sync(
|
| 322 |
+
self, requires_gradient_sync: bool, *, recurse: bool = True
|
| 323 |
+
) -> None:
|
| 324 |
+
"""
|
| 325 |
+
Sets if the module should sync gradients. This can be used to implement
|
| 326 |
+
gradient accumulation *without communication*. For HSDP, this controls
|
| 327 |
+
both reduce-scatter and all-reduce together. This is the equivalence of
|
| 328 |
+
`no_sync` in FSDP1.
|
| 329 |
+
|
| 330 |
+
Args:
|
| 331 |
+
requires_gradient_sync (bool): Whether to reduce gradients for the
|
| 332 |
+
module's parameters.
|
| 333 |
+
recurse (bool): Whether to set for all FSDP submodules or just the
|
| 334 |
+
passed-in module.
|
| 335 |
+
"""
|
| 336 |
+
self_module = cast(nn.Module, self)
|
| 337 |
+
modules = list(self_module.modules()) if recurse else [self_module]
|
| 338 |
+
for module in modules:
|
| 339 |
+
if isinstance(module, FSDPModule):
|
| 340 |
+
state = module._get_fsdp_state()
|
| 341 |
+
if fsdp_param_group := state._fsdp_param_group:
|
| 342 |
+
fsdp_param_group.reduce_grads = requires_gradient_sync
|
| 343 |
+
fsdp_param_group.all_reduce_grads = requires_gradient_sync
|
| 344 |
+
|
| 345 |
+
def set_requires_all_reduce(
|
| 346 |
+
self, requires_all_reduce: bool, *, recurse: bool = True
|
| 347 |
+
) -> None:
|
| 348 |
+
"""
|
| 349 |
+
Sets if the module should all-reduce gradients. This can be used to
|
| 350 |
+
implement gradient accumulation with only reduce-scatter but not
|
| 351 |
+
all-reduce for HSDP.
|
| 352 |
+
"""
|
| 353 |
+
self_module = cast(nn.Module, self)
|
| 354 |
+
modules = list(self_module.modules()) if recurse else [self_module]
|
| 355 |
+
for module in modules:
|
| 356 |
+
if isinstance(module, FSDPModule):
|
| 357 |
+
state = module._get_fsdp_state()
|
| 358 |
+
if fsdp_param_group := state._fsdp_param_group:
|
| 359 |
+
fsdp_param_group.all_reduce_grads = requires_all_reduce
|
| 360 |
+
|
| 361 |
+
def set_reshard_after_forward(
|
| 362 |
+
self, reshard_after_forward: bool, recurse: bool = True
|
| 363 |
+
) -> None:
|
| 364 |
+
"""
|
| 365 |
+
Sets if the module should reshard parameters after forward. This can be
|
| 366 |
+
used to change the ``reshard_after_forward`` FSDP arg at runtime. For
|
| 367 |
+
example, this can be used to set the FSDP root module's value to
|
| 368 |
+
``True`` (since it is otherwise specially set to ``False``), or it can
|
| 369 |
+
set an FSDP module's value to ``False`` for running evals and set back
|
| 370 |
+
to ``True`` for training.
|
| 371 |
+
|
| 372 |
+
Args:
|
| 373 |
+
reshard_after_forward (bool): Whether to reshard parameters after
|
| 374 |
+
forward.
|
| 375 |
+
recurse (bool): Whether to set for all FSDP submodules or just the
|
| 376 |
+
passed-in module.
|
| 377 |
+
"""
|
| 378 |
+
if not isinstance(reshard_after_forward, bool):
|
| 379 |
+
raise ValueError(
|
| 380 |
+
f"reshard_after_forward should be a bool, got {type(reshard_after_forward)}"
|
| 381 |
+
)
|
| 382 |
+
self_module = cast(nn.Module, self)
|
| 383 |
+
modules = list(self_module.modules()) if recurse else [self_module]
|
| 384 |
+
for module in modules:
|
| 385 |
+
if isinstance(module, FSDPModule):
|
| 386 |
+
state = module._get_fsdp_state()
|
| 387 |
+
state._auto_reshard_after_forward = False
|
| 388 |
+
if fsdp_param_group := state._fsdp_param_group:
|
| 389 |
+
fsdp_param_group.post_forward_mesh_info = (
|
| 390 |
+
_get_post_forward_mesh_info(
|
| 391 |
+
reshard_after_forward, fsdp_param_group.mesh_info
|
| 392 |
+
)
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
def set_reshard_after_backward(
|
| 396 |
+
self, reshard_after_backward: bool, *, recurse: bool = True
|
| 397 |
+
) -> None:
|
| 398 |
+
"""
|
| 399 |
+
Sets if the module should reshard parameters after backward. This can
|
| 400 |
+
be used during gradient accumulation to trade off higher memory for
|
| 401 |
+
reduced communication since the unsharded parameters do not need to be
|
| 402 |
+
re-all-gathered before the next forward.
|
| 403 |
+
|
| 404 |
+
Args:
|
| 405 |
+
reshard_after_backward (bool): Whether to reshard parameters after
|
| 406 |
+
backward.
|
| 407 |
+
recurse (bool): Whether to set for all FSDP submodules or just the
|
| 408 |
+
passed-in module.
|
| 409 |
+
"""
|
| 410 |
+
self_module = cast(nn.Module, self)
|
| 411 |
+
modules = list(self_module.modules()) if recurse else [self_module]
|
| 412 |
+
for module in modules:
|
| 413 |
+
if isinstance(module, FSDPModule):
|
| 414 |
+
state = module._get_fsdp_state()
|
| 415 |
+
if fsdp_param_group := state._fsdp_param_group:
|
| 416 |
+
fsdp_param_group.reshard_after_backward = reshard_after_backward
|
| 417 |
+
|
| 418 |
+
def set_modules_to_forward_prefetch(self, modules: list[FSDPModule]) -> None:
|
| 419 |
+
"""
|
| 420 |
+
Sets the FSDP modules for which this FSDP module should explicitly
|
| 421 |
+
prefetch all-gathers in forward. The prefetching runs after this
|
| 422 |
+
module's all-gather copy-out.
|
| 423 |
+
|
| 424 |
+
Passing a singleton list containing the next FSDP module gives the same
|
| 425 |
+
all-gather overlap behavior as the default overlap behavior, except the
|
| 426 |
+
prefetched all-gather is issued earlier from the CPU. Passing a list
|
| 427 |
+
with at least length two is required for more aggressive overlap and
|
| 428 |
+
will use more reserved memory.
|
| 429 |
+
|
| 430 |
+
Args:
|
| 431 |
+
modules (List[FSDPModule]): FSDP modules to prefetch.
|
| 432 |
+
"""
|
| 433 |
+
_assert_all_fsdp_modules(modules)
|
| 434 |
+
self._get_fsdp_state()._states_to_forward_prefetch = [
|
| 435 |
+
module._get_fsdp_state() for module in modules
|
| 436 |
+
]
|
| 437 |
+
|
| 438 |
+
def set_modules_to_backward_prefetch(self, modules: list[FSDPModule]) -> None:
|
| 439 |
+
"""
|
| 440 |
+
Sets the FSDP modules for which this FSDP module should explicitly
|
| 441 |
+
prefetch all-gathers in backward. This overrides the default backward
|
| 442 |
+
pretching implementation that prefetches the next FSDP module based on
|
| 443 |
+
the reverse post-forward order.
|
| 444 |
+
|
| 445 |
+
Passing a singleton list containing the previous FSDP module gives the
|
| 446 |
+
same all-gather overlap behavior as the default overlap behavior.
|
| 447 |
+
Passing a list with at least length two is required for more aggressive
|
| 448 |
+
overlap and will use more reserved memory.
|
| 449 |
+
|
| 450 |
+
Args:
|
| 451 |
+
modules (List[FSDPModule]): FSDP modules to prefetch.
|
| 452 |
+
"""
|
| 453 |
+
_assert_all_fsdp_modules(modules)
|
| 454 |
+
self._get_fsdp_state()._states_to_backward_prefetch = [
|
| 455 |
+
module._get_fsdp_state() for module in modules
|
| 456 |
+
]
|
| 457 |
+
|
| 458 |
+
def set_all_reduce_hook(
|
| 459 |
+
self,
|
| 460 |
+
hook: Callable[[torch.Tensor], None],
|
| 461 |
+
*,
|
| 462 |
+
stream: Optional[torch.cuda.Stream] = None,
|
| 463 |
+
):
|
| 464 |
+
"""
|
| 465 |
+
Args:
|
| 466 |
+
hook (Callable[[torch.Tensor], None]): User-defined all-reduce hook
|
| 467 |
+
with expected signature ``hook(reduce_output: torch.Tensor) -> None``
|
| 468 |
+
where ``reduce_output`` is the reduce-scatter output if only
|
| 469 |
+
using FSDP or the all-reduce output if using native HSDP.
|
| 470 |
+
stream (Optional[torch.cuda.Stream]): Stream to run the all-reduce
|
| 471 |
+
hook in. This should only be set if not using native HSDP. If
|
| 472 |
+
using native HSDP, the hook will run in the internally defined
|
| 473 |
+
all-reduce stream used by the native HSDP all-reduce.
|
| 474 |
+
"""
|
| 475 |
+
state = self._get_fsdp_state()
|
| 476 |
+
if (fsdp_param_group := state._fsdp_param_group) is not None:
|
| 477 |
+
fsdp_param_group._all_reduce_hook = hook
|
| 478 |
+
if stream is not None:
|
| 479 |
+
if fsdp_param_group._is_hsdp:
|
| 480 |
+
raise ValueError("stream cannot be set when using native HSDP")
|
| 481 |
+
fsdp_param_group._all_reduce_hook_stream = stream
|
| 482 |
+
|
| 483 |
+
def set_post_optim_event(self, event: torch.Event) -> None:
|
| 484 |
+
"""
|
| 485 |
+
Sets a post-optimizer-step event for the root FSDP module to wait the
|
| 486 |
+
all-gather streams on.
|
| 487 |
+
|
| 488 |
+
By default, the root FSDP module waits the all-gather streams on the
|
| 489 |
+
current stream to ensure that the optimizer step has finished before
|
| 490 |
+
all-gathering. However, this may introduce false dependencies if
|
| 491 |
+
there is unrelated computation after the optimizer step. This API
|
| 492 |
+
allows the user to provide their own event to wait on. After the root
|
| 493 |
+
waits on the event, the event is discarded, so this API should be
|
| 494 |
+
called with a new event each iteration.
|
| 495 |
+
|
| 496 |
+
Args:
|
| 497 |
+
event (torch.Event): Event recorded after the optimizer step
|
| 498 |
+
to wait all-gather streams on.
|
| 499 |
+
"""
|
| 500 |
+
self._get_fsdp_state()._state_ctx.post_optim_event = event
|
| 501 |
+
|
| 502 |
+
@deprecated("Use `set_gradient_divide_factor` instead")
|
| 503 |
+
def set_reduce_scatter_divide_factor(self, factor: float) -> None:
|
| 504 |
+
"""Use :py:meth:`set_gradient_divide_factor` instead"""
|
| 505 |
+
self.set_gradient_divide_factor(factor)
|
| 506 |
+
|
| 507 |
+
def set_gradient_divide_factor(self, factor: float) -> None:
|
| 508 |
+
"""
|
| 509 |
+
Sets a custom divide factor for the gradient reduction. This might use
|
| 510 |
+
a custom reduce op using NCCL's PreMulSum, which allows multiplying by
|
| 511 |
+
the factor before reduction.
|
| 512 |
+
|
| 513 |
+
Args:
|
| 514 |
+
factor (float): Custom divide factor.
|
| 515 |
+
"""
|
| 516 |
+
state = self._get_fsdp_state()
|
| 517 |
+
if (fsdp_param_group := state._fsdp_param_group) is not None:
|
| 518 |
+
fsdp_param_group.gradient_divide_factor = factor
|
| 519 |
+
|
| 520 |
+
def set_force_sum_reduction_for_comms(self, enable: bool) -> None:
|
| 521 |
+
"""
|
| 522 |
+
Sets whether to require the low-level collective communication
|
| 523 |
+
primitives to exclusively use "sum"-type reductions, even if it comes
|
| 524 |
+
at the cost of separate additional pre- or post-scaling operations.
|
| 525 |
+
This is needed for example because NCCL currently supports zero-copy
|
| 526 |
+
transfers only for this kind of collectives.
|
| 527 |
+
|
| 528 |
+
NB: for MTIA devices, this is always implicitly enabled.
|
| 529 |
+
|
| 530 |
+
NB: if `set_all_reduce_hook` is used under FSDP setup, the caller needs
|
| 531 |
+
to ensure the custom all-reduce across FSDP units follow this strategy
|
| 532 |
+
as well, as FSDP can no longer automatically handle that.
|
| 533 |
+
|
| 534 |
+
Args:
|
| 535 |
+
enable (bool): Whether to only ever use ReduceOp.SUM for comms.
|
| 536 |
+
"""
|
| 537 |
+
state = self._get_fsdp_state()
|
| 538 |
+
if (fsdp_param_group := state._fsdp_param_group) is not None:
|
| 539 |
+
fsdp_param_group.force_sum_reduction_for_comms = enable
|
| 540 |
+
|
| 541 |
+
def set_unshard_in_backward(self, unshard_in_backward: bool) -> None:
|
| 542 |
+
"""
|
| 543 |
+
Sets whether the FSDP module's parameters need to be unsharded in
|
| 544 |
+
backward. This can be used in expert cases when the user knows that all
|
| 545 |
+
parameters in this FSDP module's parameter group are not needed for
|
| 546 |
+
backward computation (e.g. embedding).
|
| 547 |
+
"""
|
| 548 |
+
state = self._get_fsdp_state()
|
| 549 |
+
if (fsdp_param_group := state._fsdp_param_group) is not None:
|
| 550 |
+
fsdp_param_group.unshard_in_backward = unshard_in_backward
|
| 551 |
+
|
| 552 |
+
def set_allocate_memory_from_process_group_for_comm(self, enable: bool) -> None:
|
| 553 |
+
"""
|
| 554 |
+
Sets whether the temporary staging buffers used to send and receive data
|
| 555 |
+
over collective communications should be allocated using the custom
|
| 556 |
+
optimized allocator provided by the ProcessGroup itself (if any). This
|
| 557 |
+
might allow the ProcessGroup to be more efficient. For example, when
|
| 558 |
+
using NCCL, this enables it to leverage zero-copy transfers over SHARP
|
| 559 |
+
(for NVLink and/or InfiniBand).
|
| 560 |
+
|
| 561 |
+
Args:
|
| 562 |
+
enable (bool): Whether to turn on ProcessGroup allocation.
|
| 563 |
+
"""
|
| 564 |
+
state = self._get_fsdp_state()
|
| 565 |
+
if (fsdp_param_group := state._fsdp_param_group) is not None:
|
| 566 |
+
fsdp_param_group.allocate_memory_from_process_group = enable
|
| 567 |
+
|
| 568 |
+
def _set_unshard_async_op(self, async_op: bool):
|
| 569 |
+
"""
|
| 570 |
+
Sets whether to use ``async_op=True`` or ``False`` for the pre-forward
|
| 571 |
+
and pre-backward unshard op. This defaults to ``False`` but can be set
|
| 572 |
+
to ``True`` with this method.
|
| 573 |
+
|
| 574 |
+
Setting this to ``True`` allows the all-gather allocations to happen in
|
| 575 |
+
the default stream, avoiding inter-stream memory fragmentation.
|
| 576 |
+
However, you must use explicit prefetching (e.g. via :meth:`unshard`)
|
| 577 |
+
in forward to still get overlap, and the pre-all-gather ops like dtype
|
| 578 |
+
casting and copy-in will not overlap with compute.
|
| 579 |
+
"""
|
| 580 |
+
self_module = cast(nn.Module, self)
|
| 581 |
+
for module in self_module.modules():
|
| 582 |
+
if isinstance(module, FSDPModule):
|
| 583 |
+
state = module._get_fsdp_state()
|
| 584 |
+
if fsdp_param_group := state._fsdp_param_group:
|
| 585 |
+
fsdp_param_group.unshard_async_op = async_op
|
| 586 |
+
|
| 587 |
+
def _get_fsdp_state(self) -> FSDPState:
|
| 588 |
+
if (state := _get_module_fsdp_state(cast(nn.Module, self))) is None:
|
| 589 |
+
raise AssertionError(f"No FSDP state found on {self}")
|
| 590 |
+
return state
|
| 591 |
+
|
| 592 |
+
def _apply(self, *args: Any, **kwargs: Any) -> Any:
|
| 593 |
+
# Reshard to ensure that sharded parameters are registered
|
| 594 |
+
self.reshard()
|
| 595 |
+
ret = super()._apply(*args, **kwargs) # type: ignore[misc]
|
| 596 |
+
state = self._get_fsdp_state()
|
| 597 |
+
if not (fsdp_param_group := state._fsdp_param_group):
|
| 598 |
+
return ret
|
| 599 |
+
# TODO: Remove this padding logic once DTensor pads the local tensor:
|
| 600 |
+
# https://github.com/pytorch/pytorch/issues/113045
|
| 601 |
+
with torch.no_grad():
|
| 602 |
+
for fsdp_param in fsdp_param_group.fsdp_params:
|
| 603 |
+
fsdp_param.reset_sharded_param()
|
| 604 |
+
return ret
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
class UnshardHandle:
|
| 608 |
+
"""
|
| 609 |
+
A handle to wait on a :meth:`FSDPModule.unshard` op.
|
| 610 |
+
"""
|
| 611 |
+
|
| 612 |
+
def wait(self) -> None:
|
| 613 |
+
"""
|
| 614 |
+
Waits on the unshard op. This ensures that the current stream can use
|
| 615 |
+
the unsharded parameters, which are now registered to the module.
|
| 616 |
+
"""
|
| 617 |
+
return
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
class _UnshardHandleImpl(UnshardHandle):
|
| 621 |
+
def __init__(self, fsdp_param_group: Optional[FSDPParamGroup]):
|
| 622 |
+
self._fsdp_param_group = fsdp_param_group
|
| 623 |
+
|
| 624 |
+
def wait(self):
|
| 625 |
+
if self._fsdp_param_group is not None:
|
| 626 |
+
self._fsdp_param_group.wait_for_unshard()
|
| 627 |
+
# Avoid keeping a reference
|
| 628 |
+
self._fsdp_param_group = None
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def register_fsdp_forward_method(module: nn.Module, method_name: str) -> None:
|
| 632 |
+
"""
|
| 633 |
+
Registers a method on ``module`` to be considered a forward method for
|
| 634 |
+
FSDP.
|
| 635 |
+
|
| 636 |
+
FSDP all-gathers parameters pre-forward and optionally frees parameters
|
| 637 |
+
post-forward (depending on ``reshard_after_forward``). FSDP only knows to
|
| 638 |
+
do this for :meth:`nn.Module.forward` by default. This function patches a
|
| 639 |
+
user-specified method to run the pre/post-forward hooks before/after the
|
| 640 |
+
method, respectively. If ``module`` is not an :class:`FSDPModule`, then
|
| 641 |
+
this is a no-op.
|
| 642 |
+
|
| 643 |
+
Args:
|
| 644 |
+
module (nn.Module): Module to register the forward method on.
|
| 645 |
+
method_name (str): Name of the forward method.
|
| 646 |
+
"""
|
| 647 |
+
if not isinstance(module, FSDPModule):
|
| 648 |
+
# Make no-op to allow including both when using/not using FSDP
|
| 649 |
+
return
|
| 650 |
+
if not hasattr(module, method_name):
|
| 651 |
+
raise ValueError(f"{type(module)} does not have a method {method_name}")
|
| 652 |
+
orig_method = getattr(module, method_name)
|
| 653 |
+
|
| 654 |
+
@functools.wraps(orig_method)
|
| 655 |
+
def wrapped_method(self, *args, **kwargs):
|
| 656 |
+
fsdp_state = self._get_fsdp_state()
|
| 657 |
+
args, kwargs = fsdp_state._pre_forward(self, args, kwargs)
|
| 658 |
+
out = orig_method(*args, **kwargs)
|
| 659 |
+
return fsdp_state._post_forward(self, args, out)
|
| 660 |
+
|
| 661 |
+
# Use `__get__` to make `wrapped_method` an instance method
|
| 662 |
+
setattr(
|
| 663 |
+
module,
|
| 664 |
+
method_name,
|
| 665 |
+
wrapped_method.__get__(module, type(module)), # type:ignore[attr-defined]
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def _assert_all_fsdp_modules(modules: Iterable[Any]) -> None:
|
| 670 |
+
for module in modules:
|
| 671 |
+
if not isinstance(module, FSDPModule):
|
| 672 |
+
raise ValueError(f"Expects FSDPModule but got {type(module)}: {module}")
|
added_tokens.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"</tool_call>": 151658,
|
| 3 |
+
"<tool_call>": 151657,
|
| 4 |
+
"<|box_end|>": 151649,
|
| 5 |
+
"<|box_start|>": 151648,
|
| 6 |
+
"<|endoftext|>": 151643,
|
| 7 |
+
"<|file_sep|>": 151664,
|
| 8 |
+
"<|fim_middle|>": 151660,
|
| 9 |
+
"<|fim_pad|>": 151662,
|
| 10 |
+
"<|fim_prefix|>": 151659,
|
| 11 |
+
"<|fim_suffix|>": 151661,
|
| 12 |
+
"<|im_end|>": 151645,
|
| 13 |
+
"<|im_start|>": 151644,
|
| 14 |
+
"<|image_pad|>": 151655,
|
| 15 |
+
"<|object_ref_end|>": 151647,
|
| 16 |
+
"<|object_ref_start|>": 151646,
|
| 17 |
+
"<|quad_end|>": 151651,
|
| 18 |
+
"<|quad_start|>": 151650,
|
| 19 |
+
"<|repo_name|>": 151663,
|
| 20 |
+
"<|video_pad|>": 151656,
|
| 21 |
+
"<|vision_end|>": 151653,
|
| 22 |
+
"<|vision_pad|>": 151654,
|
| 23 |
+
"<|vision_start|>": 151652
|
| 24 |
+
}
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system
|
| 2 |
+
You are a helpful assistant.<|im_end|>
|
| 3 |
+
{% endif %}<|im_start|>{{ message['role'] }}
|
| 4 |
+
{% if message['content'] is string %}{{ message['content'] }}<|im_end|>
|
| 5 |
+
{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>
|
| 6 |
+
{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
|
| 7 |
+
{% endif %}
|
config.json
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"LLaVAOneVision1_5_ForConditionalGeneration"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_llavaonevision1_5.Llavaonevision1_5Config",
|
| 7 |
+
"AutoModel": "modeling_llavaonevision1_5.LLaVAOneVision1_5_ForConditionalGeneration",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_llavaonevision1_5.LLaVAOneVision1_5_ForConditionalGeneration"
|
| 9 |
+
},
|
| 10 |
+
"dtype": "bfloat16",
|
| 11 |
+
"image_token_id": 151655,
|
| 12 |
+
"model_type": "llavaonevision1_5",
|
| 13 |
+
"text_config": {
|
| 14 |
+
"attention_bias": false,
|
| 15 |
+
"attention_dropout": 0.0,
|
| 16 |
+
"head_dim": 128,
|
| 17 |
+
"hidden_act": "silu",
|
| 18 |
+
"hidden_size": 4096,
|
| 19 |
+
"image_token_id": null,
|
| 20 |
+
"initializer_range": 0.02,
|
| 21 |
+
"intermediate_size": 12288,
|
| 22 |
+
"layer_types": [
|
| 23 |
+
"full_attention",
|
| 24 |
+
"full_attention",
|
| 25 |
+
"full_attention",
|
| 26 |
+
"full_attention",
|
| 27 |
+
"full_attention",
|
| 28 |
+
"full_attention",
|
| 29 |
+
"full_attention",
|
| 30 |
+
"full_attention",
|
| 31 |
+
"full_attention",
|
| 32 |
+
"full_attention",
|
| 33 |
+
"full_attention",
|
| 34 |
+
"full_attention",
|
| 35 |
+
"full_attention",
|
| 36 |
+
"full_attention",
|
| 37 |
+
"full_attention",
|
| 38 |
+
"full_attention",
|
| 39 |
+
"full_attention",
|
| 40 |
+
"full_attention",
|
| 41 |
+
"full_attention",
|
| 42 |
+
"full_attention",
|
| 43 |
+
"full_attention",
|
| 44 |
+
"full_attention",
|
| 45 |
+
"full_attention",
|
| 46 |
+
"full_attention",
|
| 47 |
+
"full_attention",
|
| 48 |
+
"full_attention",
|
| 49 |
+
"full_attention",
|
| 50 |
+
"full_attention",
|
| 51 |
+
"full_attention",
|
| 52 |
+
"full_attention",
|
| 53 |
+
"full_attention",
|
| 54 |
+
"full_attention",
|
| 55 |
+
"full_attention",
|
| 56 |
+
"full_attention",
|
| 57 |
+
"full_attention",
|
| 58 |
+
"full_attention"
|
| 59 |
+
],
|
| 60 |
+
"max_position_embeddings": 32768,
|
| 61 |
+
"max_window_layers": 36,
|
| 62 |
+
"model_type": "LLaVAOneVision1_5_text",
|
| 63 |
+
"num_attention_heads": 32,
|
| 64 |
+
"num_hidden_layers": 36,
|
| 65 |
+
"num_key_value_heads": 8,
|
| 66 |
+
"rms_norm_eps": 1e-06,
|
| 67 |
+
"rope_scaling": null,
|
| 68 |
+
"rope_theta": 1000000.0,
|
| 69 |
+
"sliding_window": null,
|
| 70 |
+
"use_cache": true,
|
| 71 |
+
"use_sliding_window": false,
|
| 72 |
+
"video_token_id": null,
|
| 73 |
+
"vocab_size": 151936
|
| 74 |
+
},
|
| 75 |
+
"transformers_version": "4.56.1",
|
| 76 |
+
"video_token_id": 151656,
|
| 77 |
+
"vision_config": {
|
| 78 |
+
"depth": 24,
|
| 79 |
+
"embed_dim": 1024,
|
| 80 |
+
"hidden_act": "gelu",
|
| 81 |
+
"hidden_size": 1024,
|
| 82 |
+
"in_channels": 3,
|
| 83 |
+
"initializer_range": 0.02,
|
| 84 |
+
"intermediate_size": 4096,
|
| 85 |
+
"layer_norm_eps": 1e-05,
|
| 86 |
+
"model_type": "rice_vit",
|
| 87 |
+
"num_heads": 16,
|
| 88 |
+
"patch_size": 14,
|
| 89 |
+
"spatial_merge_size": 2,
|
| 90 |
+
"temporal_patch_size": 1,
|
| 91 |
+
"text_hidden_size": 4096
|
| 92 |
+
},
|
| 93 |
+
"vocab_size": 151936
|
| 94 |
+
}
|
configuration_llavaonevision1_5.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from transformers.configuration_utils import PretrainedConfig, layer_type_validation
|
| 16 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
| 17 |
+
from transformers.utils import logging
|
| 18 |
+
|
| 19 |
+
logger = logging.get_logger(__name__)
|
| 20 |
+
|
| 21 |
+
class RiceConfig(PretrainedConfig):
|
| 22 |
+
model_type = "rice_vit"
|
| 23 |
+
base_config_key = "vision_config"
|
| 24 |
+
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
depth=24,
|
| 28 |
+
embed_dim=1024,
|
| 29 |
+
hidden_size=1024,
|
| 30 |
+
hidden_act="gelu",
|
| 31 |
+
intermediate_size=4096,
|
| 32 |
+
num_heads=16,
|
| 33 |
+
in_channels=3,
|
| 34 |
+
patch_size=14,
|
| 35 |
+
spatial_merge_size=2,
|
| 36 |
+
temporal_patch_size=1,
|
| 37 |
+
initializer_range=0.02,
|
| 38 |
+
layer_norm_eps=1e-05,
|
| 39 |
+
text_hidden_size=2560,
|
| 40 |
+
**kwargs,
|
| 41 |
+
):
|
| 42 |
+
super().__init__(**kwargs)
|
| 43 |
+
|
| 44 |
+
self.depth = depth
|
| 45 |
+
self.embed_dim = embed_dim
|
| 46 |
+
self.hidden_size = hidden_size
|
| 47 |
+
self.hidden_act = hidden_act
|
| 48 |
+
self.intermediate_size = intermediate_size
|
| 49 |
+
self.num_heads = num_heads
|
| 50 |
+
self.in_channels = in_channels
|
| 51 |
+
self.patch_size = patch_size
|
| 52 |
+
self.spatial_merge_size = spatial_merge_size
|
| 53 |
+
self.temporal_patch_size = temporal_patch_size
|
| 54 |
+
self.initializer_range = initializer_range
|
| 55 |
+
self.layer_norm_eps = layer_norm_eps
|
| 56 |
+
self.text_hidden_size = text_hidden_size
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class LLaVAOneVision1_5_TextConfig(PretrainedConfig):
|
| 60 |
+
r"""
|
| 61 |
+
Args:
|
| 62 |
+
vocab_size (`int`, *optional*, defaults to 152064):
|
| 63 |
+
Vocabulary size of the Qwen2VL model. Defines the number of different tokens that can be represented by the
|
| 64 |
+
`inputs_ids` passed when calling [`Qwen2VLModel`]
|
| 65 |
+
hidden_size (`int`, *optional*, defaults to 8192):
|
| 66 |
+
Dimension of the hidden representations.
|
| 67 |
+
intermediate_size (`int`, *optional*, defaults to 29568):
|
| 68 |
+
Dimension of the MLP representations.
|
| 69 |
+
num_hidden_layers (`int`, *optional*, defaults to 80):
|
| 70 |
+
Number of hidden layers in the Transformer encoder.
|
| 71 |
+
num_attention_heads (`int`, *optional*, defaults to 64):
|
| 72 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 73 |
+
num_key_value_heads (`int`, *optional*, defaults to 8):
|
| 74 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 75 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 76 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 77 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 78 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 79 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
|
| 80 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 81 |
+
The non-linear activation function (function or string) in the decoder.
|
| 82 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
| 83 |
+
The maximum sequence length that this model might ever be used with.
|
| 84 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 85 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 86 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 87 |
+
The epsilon used by the rms normalization layers.
|
| 88 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 89 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 90 |
+
relevant if `config.is_decoder=True`.
|
| 91 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 92 |
+
Whether the model's input and output word embeddings should be tied.
|
| 93 |
+
rope_theta (`float`, *optional*, defaults to 1000000.0):
|
| 94 |
+
The base period of the RoPE embeddings.
|
| 95 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
| 96 |
+
Whether to use sliding window attention.
|
| 97 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
| 98 |
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
| 99 |
+
max_window_layers (`int`, *optional*, defaults to 80):
|
| 100 |
+
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
|
| 101 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 102 |
+
The dropout ratio for the attention probabilities.
|
| 103 |
+
rope_scaling (`Dict`, *optional*):
|
| 104 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
| 105 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
| 106 |
+
accordingly.
|
| 107 |
+
Expected contents:
|
| 108 |
+
`rope_type` (`str`):
|
| 109 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
| 110 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
| 111 |
+
`factor` (`float`, *optional*):
|
| 112 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
| 113 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
| 114 |
+
original maximum pre-trained length.
|
| 115 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
| 116 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
| 117 |
+
pretraining.
|
| 118 |
+
`attention_factor` (`float`, *optional*):
|
| 119 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
| 120 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
| 121 |
+
`factor` field to infer the suggested value.
|
| 122 |
+
`beta_fast` (`float`, *optional*):
|
| 123 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
| 124 |
+
ramp function. If unspecified, it defaults to 32.
|
| 125 |
+
`beta_slow` (`float`, *optional*):
|
| 126 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
| 127 |
+
ramp function. If unspecified, it defaults to 1.
|
| 128 |
+
`short_factor` (`List[float]`, *optional*):
|
| 129 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
| 130 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 131 |
+
size divided by the number of attention heads divided by 2
|
| 132 |
+
`long_factor` (`List[float]`, *optional*):
|
| 133 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
| 134 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 135 |
+
size divided by the number of attention heads divided by 2
|
| 136 |
+
`low_freq_factor` (`float`, *optional*):
|
| 137 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
| 138 |
+
`high_freq_factor` (`float`, *optional*):
|
| 139 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
| 140 |
+
image_token_id (`int`, *optional*):
|
| 141 |
+
Token index used as placeholder for image embeddings.
|
| 142 |
+
video_token_id (`int`, *optional*):
|
| 143 |
+
Token index used as placeholder for video embeddings.
|
| 144 |
+
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
model_type = "LLaVAOneVision1_5_text"
|
| 148 |
+
base_config_key = "text_config"
|
| 149 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 150 |
+
# Default tensor parallel plan for base model `Qwen2VL`
|
| 151 |
+
base_model_tp_plan = {
|
| 152 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 153 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 154 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 155 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 156 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 157 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 158 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 159 |
+
}
|
| 160 |
+
base_model_pp_plan = {
|
| 161 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 162 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 163 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
def __init__(
|
| 167 |
+
self,
|
| 168 |
+
vocab_size=151936,
|
| 169 |
+
hidden_size=4096,
|
| 170 |
+
intermediate_size=12288,
|
| 171 |
+
num_hidden_layers=36,
|
| 172 |
+
num_attention_heads=32,
|
| 173 |
+
num_key_value_heads=8,
|
| 174 |
+
head_dim=128,
|
| 175 |
+
hidden_act="silu",
|
| 176 |
+
max_position_embeddings=32768,
|
| 177 |
+
initializer_range=0.02,
|
| 178 |
+
rms_norm_eps=1e-06,
|
| 179 |
+
use_cache=True,
|
| 180 |
+
tie_word_embeddings=False,
|
| 181 |
+
rope_theta=1000000.0,
|
| 182 |
+
attention_bias=False,
|
| 183 |
+
use_sliding_window=False,
|
| 184 |
+
sliding_window=None,
|
| 185 |
+
max_window_layers=36,
|
| 186 |
+
attention_dropout=0.0,
|
| 187 |
+
rope_scaling=None,
|
| 188 |
+
layer_types=None,
|
| 189 |
+
image_token_id=None,
|
| 190 |
+
video_token_id=None,
|
| 191 |
+
**kwargs,
|
| 192 |
+
):
|
| 193 |
+
self.vocab_size = vocab_size
|
| 194 |
+
self.max_position_embeddings = max_position_embeddings
|
| 195 |
+
self.hidden_size = hidden_size
|
| 196 |
+
self.intermediate_size = intermediate_size
|
| 197 |
+
self.num_hidden_layers = num_hidden_layers
|
| 198 |
+
self.num_attention_heads = num_attention_heads
|
| 199 |
+
self.use_sliding_window = use_sliding_window
|
| 200 |
+
self.sliding_window = sliding_window
|
| 201 |
+
self.max_window_layers = max_window_layers
|
| 202 |
+
|
| 203 |
+
# for backward compatibility
|
| 204 |
+
if num_key_value_heads is None:
|
| 205 |
+
num_key_value_heads = num_attention_heads
|
| 206 |
+
|
| 207 |
+
self.num_key_value_heads = num_key_value_heads
|
| 208 |
+
self.head_dim = head_dim
|
| 209 |
+
self.hidden_act = hidden_act
|
| 210 |
+
self.initializer_range = initializer_range
|
| 211 |
+
self.rms_norm_eps = rms_norm_eps
|
| 212 |
+
self.use_cache = use_cache
|
| 213 |
+
self.rope_theta = rope_theta
|
| 214 |
+
self.attention_dropout = attention_dropout
|
| 215 |
+
self.rope_scaling = rope_scaling
|
| 216 |
+
self.attention_bias = attention_bias
|
| 217 |
+
self.tie_word_embeddings = tie_word_embeddings
|
| 218 |
+
|
| 219 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 220 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
| 221 |
+
# and change type from 'mrope' to 'default' because `mrope` does default RoPE calculations
|
| 222 |
+
# one can set it to "linear"/"dynamic" etc. to have scaled RoPE
|
| 223 |
+
# TODO: @raushan update config in the hub
|
| 224 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 225 |
+
if self.rope_scaling["type"] == "mrope":
|
| 226 |
+
self.rope_scaling["type"] = "default"
|
| 227 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 228 |
+
rope_config_validation(self, ignore_keys={"mrope_section"})
|
| 229 |
+
self.image_token_id = image_token_id
|
| 230 |
+
self.video_token_id = video_token_id
|
| 231 |
+
|
| 232 |
+
self.layer_types = layer_types
|
| 233 |
+
if self.layer_types is None:
|
| 234 |
+
self.layer_types = [
|
| 235 |
+
"sliding_attention"
|
| 236 |
+
if self.sliding_window is not None and i >= self.max_window_layers
|
| 237 |
+
else "full_attention"
|
| 238 |
+
for i in range(self.num_hidden_layers)
|
| 239 |
+
]
|
| 240 |
+
layer_type_validation(self.layer_types)
|
| 241 |
+
|
| 242 |
+
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class Llavaonevision1_5Config(PretrainedConfig):
|
| 246 |
+
r"""
|
| 247 |
+
Args:
|
| 248 |
+
text_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `LLaVAOneVision1_5_TextConfig`):
|
| 249 |
+
The config object or dictionary of the text backbone.
|
| 250 |
+
vision_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `LLaVAOneVision1_5_VisionConfig`):
|
| 251 |
+
The config object or dictionary of the vision backbone.
|
| 252 |
+
image_token_id (`int`, *optional*, defaults to 151655):
|
| 253 |
+
The image token index to encode the image prompt.
|
| 254 |
+
video_token_id (`int`, *optional*, defaults to 151656):
|
| 255 |
+
The video token index to encode the image prompt.
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
model_type = "llavaonevision1_5"
|
| 259 |
+
sub_configs = {"vision_config": RiceConfig, "text_config": LLaVAOneVision1_5_TextConfig}
|
| 260 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 261 |
+
|
| 262 |
+
def __init__(
|
| 263 |
+
self,
|
| 264 |
+
text_config=None,
|
| 265 |
+
vision_config=None,
|
| 266 |
+
image_token_id=151655,
|
| 267 |
+
video_token_id=151656,
|
| 268 |
+
vocab_size=152064,
|
| 269 |
+
**kwargs,
|
| 270 |
+
):
|
| 271 |
+
if isinstance(vision_config, dict):
|
| 272 |
+
self.vision_config = self.sub_configs["vision_config"](**vision_config)
|
| 273 |
+
elif vision_config is None:
|
| 274 |
+
self.vision_config = self.sub_configs["vision_config"]()
|
| 275 |
+
|
| 276 |
+
if isinstance(text_config, dict):
|
| 277 |
+
self.text_config = self.sub_configs["text_config"](**text_config)
|
| 278 |
+
elif text_config is None:
|
| 279 |
+
# For BC use all kwargs to init `TextConfig`
|
| 280 |
+
self.text_config = self.sub_configs["text_config"](**kwargs)
|
| 281 |
+
|
| 282 |
+
self.image_token_id = image_token_id
|
| 283 |
+
self.video_token_id = video_token_id
|
| 284 |
+
self.vocab_size = vocab_size
|
| 285 |
+
|
| 286 |
+
super().__init__(**kwargs)
|
| 287 |
+
|
| 288 |
+
__all__ = ["Llavaonevision1_5Config", "LLaVAOneVision1_5_TextConfig"]
|
generation_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 151643,
|
| 4 |
+
"do_sample": true,
|
| 5 |
+
"eos_token_id": 151645,
|
| 6 |
+
"pad_token_id": 151643,
|
| 7 |
+
"repetition_penalty": 1.05,
|
| 8 |
+
"temperature": 1e-06,
|
| 9 |
+
"transformers_version": "4.56.1"
|
| 10 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model-00001-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0294027929d67d68ef00ac85691fb4c5b54a86c9a320df39e0e1ed19a53874b4
|
| 3 |
+
size 4904122744
|
model-00002-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b9665b3077463f543af0a8e5603c50c8048d60b6a5f7d29559cf0ca700f9b36f
|
| 3 |
+
size 4915960344
|
model-00003-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0b7173f596166206d13a3f0b49e9d807f5e8cc6920a7df94f89e605be8abb6b5
|
| 3 |
+
size 4915960368
|
model-00004-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e6d884741c523efa028a24ff497ff25af25fb4e885f140f41f11a0d46ad18ca1
|
| 3 |
+
size 2318463256
|
model.safetensors.index.json
ADDED
|
@@ -0,0 +1,706 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"metadata": {
|
| 3 |
+
"total_parameters": 8527214624,
|
| 4 |
+
"total_size": 17054429248
|
| 5 |
+
},
|
| 6 |
+
"weight_map": {
|
| 7 |
+
"lm_head.weight": "model-00004-of-00004.safetensors",
|
| 8 |
+
"model.embed_tokens.weight": "model-00001-of-00004.safetensors",
|
| 9 |
+
"model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 10 |
+
"model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 11 |
+
"model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 12 |
+
"model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 13 |
+
"model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 14 |
+
"model.layers.0.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
|
| 15 |
+
"model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 16 |
+
"model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 17 |
+
"model.layers.0.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
|
| 18 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 19 |
+
"model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 20 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 21 |
+
"model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 22 |
+
"model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 23 |
+
"model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 24 |
+
"model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 25 |
+
"model.layers.1.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
|
| 26 |
+
"model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 27 |
+
"model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 28 |
+
"model.layers.1.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
|
| 29 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 30 |
+
"model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 31 |
+
"model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 32 |
+
"model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 33 |
+
"model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 34 |
+
"model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 35 |
+
"model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 36 |
+
"model.layers.10.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 37 |
+
"model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 38 |
+
"model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 39 |
+
"model.layers.10.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 40 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 41 |
+
"model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 42 |
+
"model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 43 |
+
"model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 44 |
+
"model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 45 |
+
"model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 46 |
+
"model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 47 |
+
"model.layers.11.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 48 |
+
"model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 49 |
+
"model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 50 |
+
"model.layers.11.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 51 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 52 |
+
"model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 53 |
+
"model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 54 |
+
"model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 55 |
+
"model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 56 |
+
"model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 57 |
+
"model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 58 |
+
"model.layers.12.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 59 |
+
"model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 60 |
+
"model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 61 |
+
"model.layers.12.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 62 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 63 |
+
"model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 64 |
+
"model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 65 |
+
"model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 66 |
+
"model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 67 |
+
"model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 68 |
+
"model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 69 |
+
"model.layers.13.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 70 |
+
"model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 71 |
+
"model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 72 |
+
"model.layers.13.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 73 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 74 |
+
"model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 75 |
+
"model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 76 |
+
"model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 77 |
+
"model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 78 |
+
"model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 79 |
+
"model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 80 |
+
"model.layers.14.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 81 |
+
"model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 82 |
+
"model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 83 |
+
"model.layers.14.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 84 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 85 |
+
"model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 86 |
+
"model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 87 |
+
"model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 88 |
+
"model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 89 |
+
"model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 90 |
+
"model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 91 |
+
"model.layers.15.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 92 |
+
"model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 93 |
+
"model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 94 |
+
"model.layers.15.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 95 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 96 |
+
"model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 97 |
+
"model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 98 |
+
"model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 99 |
+
"model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 100 |
+
"model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 101 |
+
"model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 102 |
+
"model.layers.16.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 103 |
+
"model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 104 |
+
"model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 105 |
+
"model.layers.16.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 106 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 107 |
+
"model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 108 |
+
"model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 109 |
+
"model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 110 |
+
"model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 111 |
+
"model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 112 |
+
"model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 113 |
+
"model.layers.17.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 114 |
+
"model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 115 |
+
"model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 116 |
+
"model.layers.17.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 117 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 118 |
+
"model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 119 |
+
"model.layers.18.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 120 |
+
"model.layers.18.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 121 |
+
"model.layers.18.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 122 |
+
"model.layers.18.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 123 |
+
"model.layers.18.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 124 |
+
"model.layers.18.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 125 |
+
"model.layers.18.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 126 |
+
"model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 127 |
+
"model.layers.18.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 128 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 129 |
+
"model.layers.18.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 130 |
+
"model.layers.19.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 131 |
+
"model.layers.19.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 132 |
+
"model.layers.19.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 133 |
+
"model.layers.19.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 134 |
+
"model.layers.19.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 135 |
+
"model.layers.19.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 136 |
+
"model.layers.19.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 137 |
+
"model.layers.19.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 138 |
+
"model.layers.19.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 139 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 140 |
+
"model.layers.19.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 141 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 142 |
+
"model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 143 |
+
"model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 144 |
+
"model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 145 |
+
"model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 146 |
+
"model.layers.2.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
|
| 147 |
+
"model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 148 |
+
"model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 149 |
+
"model.layers.2.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
|
| 150 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 151 |
+
"model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 152 |
+
"model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 153 |
+
"model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 154 |
+
"model.layers.20.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 155 |
+
"model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 156 |
+
"model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 157 |
+
"model.layers.20.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 158 |
+
"model.layers.20.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 159 |
+
"model.layers.20.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 160 |
+
"model.layers.20.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 161 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 162 |
+
"model.layers.20.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 163 |
+
"model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 164 |
+
"model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 165 |
+
"model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 166 |
+
"model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 167 |
+
"model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 168 |
+
"model.layers.21.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 169 |
+
"model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 170 |
+
"model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 171 |
+
"model.layers.21.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 172 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 173 |
+
"model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 174 |
+
"model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 175 |
+
"model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 176 |
+
"model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 177 |
+
"model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 178 |
+
"model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 179 |
+
"model.layers.22.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 180 |
+
"model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 181 |
+
"model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 182 |
+
"model.layers.22.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 183 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 184 |
+
"model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 185 |
+
"model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 186 |
+
"model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 187 |
+
"model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 188 |
+
"model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 189 |
+
"model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 190 |
+
"model.layers.23.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 191 |
+
"model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 192 |
+
"model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 193 |
+
"model.layers.23.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 194 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 195 |
+
"model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 196 |
+
"model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 197 |
+
"model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 198 |
+
"model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 199 |
+
"model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 200 |
+
"model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 201 |
+
"model.layers.24.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 202 |
+
"model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 203 |
+
"model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 204 |
+
"model.layers.24.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 205 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 206 |
+
"model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 207 |
+
"model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 208 |
+
"model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 209 |
+
"model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 210 |
+
"model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 211 |
+
"model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 212 |
+
"model.layers.25.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 213 |
+
"model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 214 |
+
"model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 215 |
+
"model.layers.25.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 216 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 217 |
+
"model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 218 |
+
"model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 219 |
+
"model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 220 |
+
"model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 221 |
+
"model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 222 |
+
"model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 223 |
+
"model.layers.26.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 224 |
+
"model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 225 |
+
"model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 226 |
+
"model.layers.26.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 227 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 228 |
+
"model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 229 |
+
"model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 230 |
+
"model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 231 |
+
"model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 232 |
+
"model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 233 |
+
"model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 234 |
+
"model.layers.27.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 235 |
+
"model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 236 |
+
"model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 237 |
+
"model.layers.27.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 238 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 239 |
+
"model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 240 |
+
"model.layers.28.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 241 |
+
"model.layers.28.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 242 |
+
"model.layers.28.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 243 |
+
"model.layers.28.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 244 |
+
"model.layers.28.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 245 |
+
"model.layers.28.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 246 |
+
"model.layers.28.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 247 |
+
"model.layers.28.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 248 |
+
"model.layers.28.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 249 |
+
"model.layers.28.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 250 |
+
"model.layers.28.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 251 |
+
"model.layers.29.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 252 |
+
"model.layers.29.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 253 |
+
"model.layers.29.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 254 |
+
"model.layers.29.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 255 |
+
"model.layers.29.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 256 |
+
"model.layers.29.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 257 |
+
"model.layers.29.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 258 |
+
"model.layers.29.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 259 |
+
"model.layers.29.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 260 |
+
"model.layers.29.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 261 |
+
"model.layers.29.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 262 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 263 |
+
"model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 264 |
+
"model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 265 |
+
"model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 266 |
+
"model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 267 |
+
"model.layers.3.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
|
| 268 |
+
"model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 269 |
+
"model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 270 |
+
"model.layers.3.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
|
| 271 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 272 |
+
"model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 273 |
+
"model.layers.30.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 274 |
+
"model.layers.30.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 275 |
+
"model.layers.30.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 276 |
+
"model.layers.30.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 277 |
+
"model.layers.30.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 278 |
+
"model.layers.30.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 279 |
+
"model.layers.30.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 280 |
+
"model.layers.30.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 281 |
+
"model.layers.30.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 282 |
+
"model.layers.30.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 283 |
+
"model.layers.30.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 284 |
+
"model.layers.31.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 285 |
+
"model.layers.31.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 286 |
+
"model.layers.31.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 287 |
+
"model.layers.31.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 288 |
+
"model.layers.31.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 289 |
+
"model.layers.31.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 290 |
+
"model.layers.31.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 291 |
+
"model.layers.31.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 292 |
+
"model.layers.31.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 293 |
+
"model.layers.31.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 294 |
+
"model.layers.31.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 295 |
+
"model.layers.32.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 296 |
+
"model.layers.32.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 297 |
+
"model.layers.32.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 298 |
+
"model.layers.32.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 299 |
+
"model.layers.32.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 300 |
+
"model.layers.32.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 301 |
+
"model.layers.32.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 302 |
+
"model.layers.32.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 303 |
+
"model.layers.32.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 304 |
+
"model.layers.32.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 305 |
+
"model.layers.32.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 306 |
+
"model.layers.33.input_layernorm.weight": "model-00004-of-00004.safetensors",
|
| 307 |
+
"model.layers.33.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
|
| 308 |
+
"model.layers.33.mlp.gate_proj.weight": "model-00004-of-00004.safetensors",
|
| 309 |
+
"model.layers.33.mlp.up_proj.weight": "model-00004-of-00004.safetensors",
|
| 310 |
+
"model.layers.33.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
|
| 311 |
+
"model.layers.33.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
|
| 312 |
+
"model.layers.33.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 313 |
+
"model.layers.33.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 314 |
+
"model.layers.33.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
|
| 315 |
+
"model.layers.33.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 316 |
+
"model.layers.33.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 317 |
+
"model.layers.34.input_layernorm.weight": "model-00004-of-00004.safetensors",
|
| 318 |
+
"model.layers.34.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
|
| 319 |
+
"model.layers.34.mlp.gate_proj.weight": "model-00004-of-00004.safetensors",
|
| 320 |
+
"model.layers.34.mlp.up_proj.weight": "model-00004-of-00004.safetensors",
|
| 321 |
+
"model.layers.34.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
|
| 322 |
+
"model.layers.34.self_attn.k_norm.weight": "model-00004-of-00004.safetensors",
|
| 323 |
+
"model.layers.34.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
|
| 324 |
+
"model.layers.34.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
|
| 325 |
+
"model.layers.34.self_attn.q_norm.weight": "model-00004-of-00004.safetensors",
|
| 326 |
+
"model.layers.34.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
|
| 327 |
+
"model.layers.34.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
|
| 328 |
+
"model.layers.35.input_layernorm.weight": "model-00004-of-00004.safetensors",
|
| 329 |
+
"model.layers.35.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
|
| 330 |
+
"model.layers.35.mlp.gate_proj.weight": "model-00004-of-00004.safetensors",
|
| 331 |
+
"model.layers.35.mlp.up_proj.weight": "model-00004-of-00004.safetensors",
|
| 332 |
+
"model.layers.35.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
|
| 333 |
+
"model.layers.35.self_attn.k_norm.weight": "model-00004-of-00004.safetensors",
|
| 334 |
+
"model.layers.35.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
|
| 335 |
+
"model.layers.35.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
|
| 336 |
+
"model.layers.35.self_attn.q_norm.weight": "model-00004-of-00004.safetensors",
|
| 337 |
+
"model.layers.35.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
|
| 338 |
+
"model.layers.35.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
|
| 339 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 340 |
+
"model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 341 |
+
"model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 342 |
+
"model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 343 |
+
"model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 344 |
+
"model.layers.4.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
|
| 345 |
+
"model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 346 |
+
"model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 347 |
+
"model.layers.4.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
|
| 348 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 349 |
+
"model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 350 |
+
"model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 351 |
+
"model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 352 |
+
"model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 353 |
+
"model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 354 |
+
"model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 355 |
+
"model.layers.5.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
|
| 356 |
+
"model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 357 |
+
"model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 358 |
+
"model.layers.5.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
|
| 359 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 360 |
+
"model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 361 |
+
"model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 362 |
+
"model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 363 |
+
"model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 364 |
+
"model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 365 |
+
"model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 366 |
+
"model.layers.6.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
|
| 367 |
+
"model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 368 |
+
"model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 369 |
+
"model.layers.6.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
|
| 370 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 371 |
+
"model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 372 |
+
"model.layers.7.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 373 |
+
"model.layers.7.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 374 |
+
"model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 375 |
+
"model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 376 |
+
"model.layers.7.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 377 |
+
"model.layers.7.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
|
| 378 |
+
"model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 379 |
+
"model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 380 |
+
"model.layers.7.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
|
| 381 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 382 |
+
"model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 383 |
+
"model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 384 |
+
"model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 385 |
+
"model.layers.8.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 386 |
+
"model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 387 |
+
"model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 388 |
+
"model.layers.8.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 389 |
+
"model.layers.8.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 390 |
+
"model.layers.8.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 391 |
+
"model.layers.8.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 392 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 393 |
+
"model.layers.8.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 394 |
+
"model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 395 |
+
"model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 396 |
+
"model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 397 |
+
"model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 398 |
+
"model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 399 |
+
"model.layers.9.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
|
| 400 |
+
"model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 401 |
+
"model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 402 |
+
"model.layers.9.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
|
| 403 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 404 |
+
"model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 405 |
+
"model.norm.weight": "model-00004-of-00004.safetensors",
|
| 406 |
+
"visual.blocks.0.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 407 |
+
"visual.blocks.0.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 408 |
+
"visual.blocks.0.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 409 |
+
"visual.blocks.0.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 410 |
+
"visual.blocks.0.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 411 |
+
"visual.blocks.0.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 412 |
+
"visual.blocks.0.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 413 |
+
"visual.blocks.0.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 414 |
+
"visual.blocks.0.norm1.bias": "model-00001-of-00004.safetensors",
|
| 415 |
+
"visual.blocks.0.norm1.weight": "model-00001-of-00004.safetensors",
|
| 416 |
+
"visual.blocks.0.norm2.bias": "model-00001-of-00004.safetensors",
|
| 417 |
+
"visual.blocks.0.norm2.weight": "model-00001-of-00004.safetensors",
|
| 418 |
+
"visual.blocks.1.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 419 |
+
"visual.blocks.1.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 420 |
+
"visual.blocks.1.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 421 |
+
"visual.blocks.1.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 422 |
+
"visual.blocks.1.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 423 |
+
"visual.blocks.1.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 424 |
+
"visual.blocks.1.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 425 |
+
"visual.blocks.1.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 426 |
+
"visual.blocks.1.norm1.bias": "model-00001-of-00004.safetensors",
|
| 427 |
+
"visual.blocks.1.norm1.weight": "model-00001-of-00004.safetensors",
|
| 428 |
+
"visual.blocks.1.norm2.bias": "model-00001-of-00004.safetensors",
|
| 429 |
+
"visual.blocks.1.norm2.weight": "model-00001-of-00004.safetensors",
|
| 430 |
+
"visual.blocks.10.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 431 |
+
"visual.blocks.10.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 432 |
+
"visual.blocks.10.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 433 |
+
"visual.blocks.10.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 434 |
+
"visual.blocks.10.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 435 |
+
"visual.blocks.10.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 436 |
+
"visual.blocks.10.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 437 |
+
"visual.blocks.10.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 438 |
+
"visual.blocks.10.norm1.bias": "model-00001-of-00004.safetensors",
|
| 439 |
+
"visual.blocks.10.norm1.weight": "model-00001-of-00004.safetensors",
|
| 440 |
+
"visual.blocks.10.norm2.bias": "model-00001-of-00004.safetensors",
|
| 441 |
+
"visual.blocks.10.norm2.weight": "model-00001-of-00004.safetensors",
|
| 442 |
+
"visual.blocks.11.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 443 |
+
"visual.blocks.11.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 444 |
+
"visual.blocks.11.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 445 |
+
"visual.blocks.11.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 446 |
+
"visual.blocks.11.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 447 |
+
"visual.blocks.11.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 448 |
+
"visual.blocks.11.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 449 |
+
"visual.blocks.11.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 450 |
+
"visual.blocks.11.norm1.bias": "model-00001-of-00004.safetensors",
|
| 451 |
+
"visual.blocks.11.norm1.weight": "model-00001-of-00004.safetensors",
|
| 452 |
+
"visual.blocks.11.norm2.bias": "model-00001-of-00004.safetensors",
|
| 453 |
+
"visual.blocks.11.norm2.weight": "model-00001-of-00004.safetensors",
|
| 454 |
+
"visual.blocks.12.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 455 |
+
"visual.blocks.12.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 456 |
+
"visual.blocks.12.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 457 |
+
"visual.blocks.12.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 458 |
+
"visual.blocks.12.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 459 |
+
"visual.blocks.12.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 460 |
+
"visual.blocks.12.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 461 |
+
"visual.blocks.12.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 462 |
+
"visual.blocks.12.norm1.bias": "model-00001-of-00004.safetensors",
|
| 463 |
+
"visual.blocks.12.norm1.weight": "model-00001-of-00004.safetensors",
|
| 464 |
+
"visual.blocks.12.norm2.bias": "model-00001-of-00004.safetensors",
|
| 465 |
+
"visual.blocks.12.norm2.weight": "model-00001-of-00004.safetensors",
|
| 466 |
+
"visual.blocks.13.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 467 |
+
"visual.blocks.13.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 468 |
+
"visual.blocks.13.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 469 |
+
"visual.blocks.13.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 470 |
+
"visual.blocks.13.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 471 |
+
"visual.blocks.13.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 472 |
+
"visual.blocks.13.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 473 |
+
"visual.blocks.13.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 474 |
+
"visual.blocks.13.norm1.bias": "model-00001-of-00004.safetensors",
|
| 475 |
+
"visual.blocks.13.norm1.weight": "model-00001-of-00004.safetensors",
|
| 476 |
+
"visual.blocks.13.norm2.bias": "model-00001-of-00004.safetensors",
|
| 477 |
+
"visual.blocks.13.norm2.weight": "model-00001-of-00004.safetensors",
|
| 478 |
+
"visual.blocks.14.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 479 |
+
"visual.blocks.14.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 480 |
+
"visual.blocks.14.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 481 |
+
"visual.blocks.14.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 482 |
+
"visual.blocks.14.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 483 |
+
"visual.blocks.14.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 484 |
+
"visual.blocks.14.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 485 |
+
"visual.blocks.14.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 486 |
+
"visual.blocks.14.norm1.bias": "model-00001-of-00004.safetensors",
|
| 487 |
+
"visual.blocks.14.norm1.weight": "model-00001-of-00004.safetensors",
|
| 488 |
+
"visual.blocks.14.norm2.bias": "model-00001-of-00004.safetensors",
|
| 489 |
+
"visual.blocks.14.norm2.weight": "model-00001-of-00004.safetensors",
|
| 490 |
+
"visual.blocks.15.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 491 |
+
"visual.blocks.15.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 492 |
+
"visual.blocks.15.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 493 |
+
"visual.blocks.15.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 494 |
+
"visual.blocks.15.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 495 |
+
"visual.blocks.15.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 496 |
+
"visual.blocks.15.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 497 |
+
"visual.blocks.15.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 498 |
+
"visual.blocks.15.norm1.bias": "model-00001-of-00004.safetensors",
|
| 499 |
+
"visual.blocks.15.norm1.weight": "model-00001-of-00004.safetensors",
|
| 500 |
+
"visual.blocks.15.norm2.bias": "model-00001-of-00004.safetensors",
|
| 501 |
+
"visual.blocks.15.norm2.weight": "model-00001-of-00004.safetensors",
|
| 502 |
+
"visual.blocks.16.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 503 |
+
"visual.blocks.16.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 504 |
+
"visual.blocks.16.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 505 |
+
"visual.blocks.16.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 506 |
+
"visual.blocks.16.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 507 |
+
"visual.blocks.16.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 508 |
+
"visual.blocks.16.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 509 |
+
"visual.blocks.16.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 510 |
+
"visual.blocks.16.norm1.bias": "model-00001-of-00004.safetensors",
|
| 511 |
+
"visual.blocks.16.norm1.weight": "model-00001-of-00004.safetensors",
|
| 512 |
+
"visual.blocks.16.norm2.bias": "model-00001-of-00004.safetensors",
|
| 513 |
+
"visual.blocks.16.norm2.weight": "model-00001-of-00004.safetensors",
|
| 514 |
+
"visual.blocks.17.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 515 |
+
"visual.blocks.17.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 516 |
+
"visual.blocks.17.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 517 |
+
"visual.blocks.17.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 518 |
+
"visual.blocks.17.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 519 |
+
"visual.blocks.17.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 520 |
+
"visual.blocks.17.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 521 |
+
"visual.blocks.17.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 522 |
+
"visual.blocks.17.norm1.bias": "model-00001-of-00004.safetensors",
|
| 523 |
+
"visual.blocks.17.norm1.weight": "model-00001-of-00004.safetensors",
|
| 524 |
+
"visual.blocks.17.norm2.bias": "model-00001-of-00004.safetensors",
|
| 525 |
+
"visual.blocks.17.norm2.weight": "model-00001-of-00004.safetensors",
|
| 526 |
+
"visual.blocks.18.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 527 |
+
"visual.blocks.18.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 528 |
+
"visual.blocks.18.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 529 |
+
"visual.blocks.18.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 530 |
+
"visual.blocks.18.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 531 |
+
"visual.blocks.18.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 532 |
+
"visual.blocks.18.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 533 |
+
"visual.blocks.18.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 534 |
+
"visual.blocks.18.norm1.bias": "model-00001-of-00004.safetensors",
|
| 535 |
+
"visual.blocks.18.norm1.weight": "model-00001-of-00004.safetensors",
|
| 536 |
+
"visual.blocks.18.norm2.bias": "model-00001-of-00004.safetensors",
|
| 537 |
+
"visual.blocks.18.norm2.weight": "model-00001-of-00004.safetensors",
|
| 538 |
+
"visual.blocks.19.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 539 |
+
"visual.blocks.19.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 540 |
+
"visual.blocks.19.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 541 |
+
"visual.blocks.19.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 542 |
+
"visual.blocks.19.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 543 |
+
"visual.blocks.19.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 544 |
+
"visual.blocks.19.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 545 |
+
"visual.blocks.19.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 546 |
+
"visual.blocks.19.norm1.bias": "model-00001-of-00004.safetensors",
|
| 547 |
+
"visual.blocks.19.norm1.weight": "model-00001-of-00004.safetensors",
|
| 548 |
+
"visual.blocks.19.norm2.bias": "model-00001-of-00004.safetensors",
|
| 549 |
+
"visual.blocks.19.norm2.weight": "model-00001-of-00004.safetensors",
|
| 550 |
+
"visual.blocks.2.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 551 |
+
"visual.blocks.2.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 552 |
+
"visual.blocks.2.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 553 |
+
"visual.blocks.2.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 554 |
+
"visual.blocks.2.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 555 |
+
"visual.blocks.2.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 556 |
+
"visual.blocks.2.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 557 |
+
"visual.blocks.2.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 558 |
+
"visual.blocks.2.norm1.bias": "model-00001-of-00004.safetensors",
|
| 559 |
+
"visual.blocks.2.norm1.weight": "model-00001-of-00004.safetensors",
|
| 560 |
+
"visual.blocks.2.norm2.bias": "model-00001-of-00004.safetensors",
|
| 561 |
+
"visual.blocks.2.norm2.weight": "model-00001-of-00004.safetensors",
|
| 562 |
+
"visual.blocks.20.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 563 |
+
"visual.blocks.20.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 564 |
+
"visual.blocks.20.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 565 |
+
"visual.blocks.20.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 566 |
+
"visual.blocks.20.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 567 |
+
"visual.blocks.20.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 568 |
+
"visual.blocks.20.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 569 |
+
"visual.blocks.20.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 570 |
+
"visual.blocks.20.norm1.bias": "model-00001-of-00004.safetensors",
|
| 571 |
+
"visual.blocks.20.norm1.weight": "model-00001-of-00004.safetensors",
|
| 572 |
+
"visual.blocks.20.norm2.bias": "model-00001-of-00004.safetensors",
|
| 573 |
+
"visual.blocks.20.norm2.weight": "model-00001-of-00004.safetensors",
|
| 574 |
+
"visual.blocks.21.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 575 |
+
"visual.blocks.21.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 576 |
+
"visual.blocks.21.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 577 |
+
"visual.blocks.21.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 578 |
+
"visual.blocks.21.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 579 |
+
"visual.blocks.21.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 580 |
+
"visual.blocks.21.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 581 |
+
"visual.blocks.21.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 582 |
+
"visual.blocks.21.norm1.bias": "model-00001-of-00004.safetensors",
|
| 583 |
+
"visual.blocks.21.norm1.weight": "model-00001-of-00004.safetensors",
|
| 584 |
+
"visual.blocks.21.norm2.bias": "model-00001-of-00004.safetensors",
|
| 585 |
+
"visual.blocks.21.norm2.weight": "model-00001-of-00004.safetensors",
|
| 586 |
+
"visual.blocks.22.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 587 |
+
"visual.blocks.22.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 588 |
+
"visual.blocks.22.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 589 |
+
"visual.blocks.22.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 590 |
+
"visual.blocks.22.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 591 |
+
"visual.blocks.22.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 592 |
+
"visual.blocks.22.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 593 |
+
"visual.blocks.22.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 594 |
+
"visual.blocks.22.norm1.bias": "model-00001-of-00004.safetensors",
|
| 595 |
+
"visual.blocks.22.norm1.weight": "model-00001-of-00004.safetensors",
|
| 596 |
+
"visual.blocks.22.norm2.bias": "model-00001-of-00004.safetensors",
|
| 597 |
+
"visual.blocks.22.norm2.weight": "model-00001-of-00004.safetensors",
|
| 598 |
+
"visual.blocks.23.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 599 |
+
"visual.blocks.23.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 600 |
+
"visual.blocks.23.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 601 |
+
"visual.blocks.23.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 602 |
+
"visual.blocks.23.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 603 |
+
"visual.blocks.23.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 604 |
+
"visual.blocks.23.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 605 |
+
"visual.blocks.23.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 606 |
+
"visual.blocks.23.norm1.bias": "model-00001-of-00004.safetensors",
|
| 607 |
+
"visual.blocks.23.norm1.weight": "model-00001-of-00004.safetensors",
|
| 608 |
+
"visual.blocks.23.norm2.bias": "model-00001-of-00004.safetensors",
|
| 609 |
+
"visual.blocks.23.norm2.weight": "model-00001-of-00004.safetensors",
|
| 610 |
+
"visual.blocks.3.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 611 |
+
"visual.blocks.3.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 612 |
+
"visual.blocks.3.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 613 |
+
"visual.blocks.3.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 614 |
+
"visual.blocks.3.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 615 |
+
"visual.blocks.3.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 616 |
+
"visual.blocks.3.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 617 |
+
"visual.blocks.3.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 618 |
+
"visual.blocks.3.norm1.bias": "model-00001-of-00004.safetensors",
|
| 619 |
+
"visual.blocks.3.norm1.weight": "model-00001-of-00004.safetensors",
|
| 620 |
+
"visual.blocks.3.norm2.bias": "model-00001-of-00004.safetensors",
|
| 621 |
+
"visual.blocks.3.norm2.weight": "model-00001-of-00004.safetensors",
|
| 622 |
+
"visual.blocks.4.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 623 |
+
"visual.blocks.4.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 624 |
+
"visual.blocks.4.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 625 |
+
"visual.blocks.4.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 626 |
+
"visual.blocks.4.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 627 |
+
"visual.blocks.4.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 628 |
+
"visual.blocks.4.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 629 |
+
"visual.blocks.4.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 630 |
+
"visual.blocks.4.norm1.bias": "model-00001-of-00004.safetensors",
|
| 631 |
+
"visual.blocks.4.norm1.weight": "model-00001-of-00004.safetensors",
|
| 632 |
+
"visual.blocks.4.norm2.bias": "model-00001-of-00004.safetensors",
|
| 633 |
+
"visual.blocks.4.norm2.weight": "model-00001-of-00004.safetensors",
|
| 634 |
+
"visual.blocks.5.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 635 |
+
"visual.blocks.5.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 636 |
+
"visual.blocks.5.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 637 |
+
"visual.blocks.5.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 638 |
+
"visual.blocks.5.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 639 |
+
"visual.blocks.5.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 640 |
+
"visual.blocks.5.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 641 |
+
"visual.blocks.5.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 642 |
+
"visual.blocks.5.norm1.bias": "model-00001-of-00004.safetensors",
|
| 643 |
+
"visual.blocks.5.norm1.weight": "model-00001-of-00004.safetensors",
|
| 644 |
+
"visual.blocks.5.norm2.bias": "model-00001-of-00004.safetensors",
|
| 645 |
+
"visual.blocks.5.norm2.weight": "model-00001-of-00004.safetensors",
|
| 646 |
+
"visual.blocks.6.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 647 |
+
"visual.blocks.6.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 648 |
+
"visual.blocks.6.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 649 |
+
"visual.blocks.6.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 650 |
+
"visual.blocks.6.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 651 |
+
"visual.blocks.6.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 652 |
+
"visual.blocks.6.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 653 |
+
"visual.blocks.6.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 654 |
+
"visual.blocks.6.norm1.bias": "model-00001-of-00004.safetensors",
|
| 655 |
+
"visual.blocks.6.norm1.weight": "model-00001-of-00004.safetensors",
|
| 656 |
+
"visual.blocks.6.norm2.bias": "model-00001-of-00004.safetensors",
|
| 657 |
+
"visual.blocks.6.norm2.weight": "model-00001-of-00004.safetensors",
|
| 658 |
+
"visual.blocks.7.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 659 |
+
"visual.blocks.7.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 660 |
+
"visual.blocks.7.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 661 |
+
"visual.blocks.7.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 662 |
+
"visual.blocks.7.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 663 |
+
"visual.blocks.7.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 664 |
+
"visual.blocks.7.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 665 |
+
"visual.blocks.7.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 666 |
+
"visual.blocks.7.norm1.bias": "model-00001-of-00004.safetensors",
|
| 667 |
+
"visual.blocks.7.norm1.weight": "model-00001-of-00004.safetensors",
|
| 668 |
+
"visual.blocks.7.norm2.bias": "model-00001-of-00004.safetensors",
|
| 669 |
+
"visual.blocks.7.norm2.weight": "model-00001-of-00004.safetensors",
|
| 670 |
+
"visual.blocks.8.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 671 |
+
"visual.blocks.8.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 672 |
+
"visual.blocks.8.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 673 |
+
"visual.blocks.8.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 674 |
+
"visual.blocks.8.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 675 |
+
"visual.blocks.8.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 676 |
+
"visual.blocks.8.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 677 |
+
"visual.blocks.8.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 678 |
+
"visual.blocks.8.norm1.bias": "model-00001-of-00004.safetensors",
|
| 679 |
+
"visual.blocks.8.norm1.weight": "model-00001-of-00004.safetensors",
|
| 680 |
+
"visual.blocks.8.norm2.bias": "model-00001-of-00004.safetensors",
|
| 681 |
+
"visual.blocks.8.norm2.weight": "model-00001-of-00004.safetensors",
|
| 682 |
+
"visual.blocks.9.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 683 |
+
"visual.blocks.9.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 684 |
+
"visual.blocks.9.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 685 |
+
"visual.blocks.9.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 686 |
+
"visual.blocks.9.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 687 |
+
"visual.blocks.9.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 688 |
+
"visual.blocks.9.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 689 |
+
"visual.blocks.9.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 690 |
+
"visual.blocks.9.norm1.bias": "model-00001-of-00004.safetensors",
|
| 691 |
+
"visual.blocks.9.norm1.weight": "model-00001-of-00004.safetensors",
|
| 692 |
+
"visual.blocks.9.norm2.bias": "model-00001-of-00004.safetensors",
|
| 693 |
+
"visual.blocks.9.norm2.weight": "model-00001-of-00004.safetensors",
|
| 694 |
+
"visual.class_embedding": "model-00001-of-00004.safetensors",
|
| 695 |
+
"visual.class_pos_emb": "model-00001-of-00004.safetensors",
|
| 696 |
+
"visual.merger.ln_q.bias": "model-00001-of-00004.safetensors",
|
| 697 |
+
"visual.merger.ln_q.weight": "model-00001-of-00004.safetensors",
|
| 698 |
+
"visual.merger.mlp.0.bias": "model-00001-of-00004.safetensors",
|
| 699 |
+
"visual.merger.mlp.0.weight": "model-00001-of-00004.safetensors",
|
| 700 |
+
"visual.merger.mlp.2.bias": "model-00001-of-00004.safetensors",
|
| 701 |
+
"visual.merger.mlp.2.weight": "model-00001-of-00004.safetensors",
|
| 702 |
+
"visual.patch_embed.proj.weight": "model-00001-of-00004.safetensors",
|
| 703 |
+
"visual.pre_layernorm.bias": "model-00001-of-00004.safetensors",
|
| 704 |
+
"visual.pre_layernorm.weight": "model-00001-of-00004.safetensors"
|
| 705 |
+
}
|
| 706 |
+
}
|
modeling_llavaonevision1_5.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
preprocessor_config.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"crop_size": null,
|
| 3 |
+
"data_format": "channels_first",
|
| 4 |
+
"default_to_square": true,
|
| 5 |
+
"device": null,
|
| 6 |
+
"disable_grouping": null,
|
| 7 |
+
"do_center_crop": null,
|
| 8 |
+
"do_convert_rgb": true,
|
| 9 |
+
"do_normalize": true,
|
| 10 |
+
"do_rescale": true,
|
| 11 |
+
"do_resize": true,
|
| 12 |
+
"image_mean": [
|
| 13 |
+
0.48145466,
|
| 14 |
+
0.4578275,
|
| 15 |
+
0.40821073
|
| 16 |
+
],
|
| 17 |
+
"image_processor_type": "Qwen2VLImageProcessorFast",
|
| 18 |
+
"image_std": [
|
| 19 |
+
0.26862954,
|
| 20 |
+
0.26130258,
|
| 21 |
+
0.27577711
|
| 22 |
+
],
|
| 23 |
+
"input_data_format": null,
|
| 24 |
+
"max_pixels": 3240000,
|
| 25 |
+
"merge_size": 2,
|
| 26 |
+
"min_pixels": 3136,
|
| 27 |
+
"patch_size": 14,
|
| 28 |
+
"processor_class": "Qwen2_5_VLProcessor",
|
| 29 |
+
"resample": 3,
|
| 30 |
+
"rescale_factor": 0.00392156862745098,
|
| 31 |
+
"return_tensors": null,
|
| 32 |
+
"size": {
|
| 33 |
+
"longest_edge": 3240000,
|
| 34 |
+
"shortest_edge": 3136
|
| 35 |
+
},
|
| 36 |
+
"temporal_patch_size": 1
|
| 37 |
+
}
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
"<|im_start|>",
|
| 4 |
+
"<|im_end|>",
|
| 5 |
+
"<|object_ref_start|>",
|
| 6 |
+
"<|object_ref_end|>",
|
| 7 |
+
"<|box_start|>",
|
| 8 |
+
"<|box_end|>",
|
| 9 |
+
"<|quad_start|>",
|
| 10 |
+
"<|quad_end|>",
|
| 11 |
+
"<|vision_start|>",
|
| 12 |
+
"<|vision_end|>",
|
| 13 |
+
"<|vision_pad|>",
|
| 14 |
+
"<|image_pad|>",
|
| 15 |
+
"<|video_pad|>"
|
| 16 |
+
],
|
| 17 |
+
"eos_token": {
|
| 18 |
+
"content": "<|im_end|>",
|
| 19 |
+
"lstrip": false,
|
| 20 |
+
"normalized": false,
|
| 21 |
+
"rstrip": false,
|
| 22 |
+
"single_word": false
|
| 23 |
+
},
|
| 24 |
+
"pad_token": {
|
| 25 |
+
"content": "<|endoftext|>",
|
| 26 |
+
"lstrip": false,
|
| 27 |
+
"normalized": false,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"single_word": false
|
| 30 |
+
}
|
| 31 |
+
}
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9c5ae00e602b8860cbd784ba82a8aa14e8feecec692e7076590d014d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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_prefix_space": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"151643": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"151644": {
|
| 14 |
+
"content": "<|im_start|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"151645": {
|
| 22 |
+
"content": "<|im_end|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"151646": {
|
| 30 |
+
"content": "<|object_ref_start|>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"151647": {
|
| 38 |
+
"content": "<|object_ref_end|>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"151648": {
|
| 46 |
+
"content": "<|box_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"151649": {
|
| 54 |
+
"content": "<|box_end|>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"151650": {
|
| 62 |
+
"content": "<|quad_start|>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"151651": {
|
| 70 |
+
"content": "<|quad_end|>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"151652": {
|
| 78 |
+
"content": "<|vision_start|>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"151653": {
|
| 86 |
+
"content": "<|vision_end|>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"151654": {
|
| 94 |
+
"content": "<|vision_pad|>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
},
|
| 101 |
+
"151655": {
|
| 102 |
+
"content": "<|image_pad|>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"special": true
|
| 108 |
+
},
|
| 109 |
+
"151656": {
|
| 110 |
+
"content": "<|video_pad|>",
|
| 111 |
+
"lstrip": false,
|
| 112 |
+
"normalized": false,
|
| 113 |
+
"rstrip": false,
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"special": true
|
| 116 |
+
},
|
| 117 |
+
"151657": {
|
| 118 |
+
"content": "<tool_call>",
|
| 119 |
+
"lstrip": false,
|
| 120 |
+
"normalized": false,
|
| 121 |
+
"rstrip": false,
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"special": false
|
| 124 |
+
},
|
| 125 |
+
"151658": {
|
| 126 |
+
"content": "</tool_call>",
|
| 127 |
+
"lstrip": false,
|
| 128 |
+
"normalized": false,
|
| 129 |
+
"rstrip": false,
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"special": false
|
| 132 |
+
},
|
| 133 |
+
"151659": {
|
| 134 |
+
"content": "<|fim_prefix|>",
|
| 135 |
+
"lstrip": false,
|
| 136 |
+
"normalized": false,
|
| 137 |
+
"rstrip": false,
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"special": false
|
| 140 |
+
},
|
| 141 |
+
"151660": {
|
| 142 |
+
"content": "<|fim_middle|>",
|
| 143 |
+
"lstrip": false,
|
| 144 |
+
"normalized": false,
|
| 145 |
+
"rstrip": false,
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"special": false
|
| 148 |
+
},
|
| 149 |
+
"151661": {
|
| 150 |
+
"content": "<|fim_suffix|>",
|
| 151 |
+
"lstrip": false,
|
| 152 |
+
"normalized": false,
|
| 153 |
+
"rstrip": false,
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"special": false
|
| 156 |
+
},
|
| 157 |
+
"151662": {
|
| 158 |
+
"content": "<|fim_pad|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"special": false
|
| 164 |
+
},
|
| 165 |
+
"151663": {
|
| 166 |
+
"content": "<|repo_name|>",
|
| 167 |
+
"lstrip": false,
|
| 168 |
+
"normalized": false,
|
| 169 |
+
"rstrip": false,
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"special": false
|
| 172 |
+
},
|
| 173 |
+
"151664": {
|
| 174 |
+
"content": "<|file_sep|>",
|
| 175 |
+
"lstrip": false,
|
| 176 |
+
"normalized": false,
|
| 177 |
+
"rstrip": false,
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"special": false
|
| 180 |
+
}
|
| 181 |
+
},
|
| 182 |
+
"additional_special_tokens": [
|
| 183 |
+
"<|im_start|>",
|
| 184 |
+
"<|im_end|>",
|
| 185 |
+
"<|object_ref_start|>",
|
| 186 |
+
"<|object_ref_end|>",
|
| 187 |
+
"<|box_start|>",
|
| 188 |
+
"<|box_end|>",
|
| 189 |
+
"<|quad_start|>",
|
| 190 |
+
"<|quad_end|>",
|
| 191 |
+
"<|vision_start|>",
|
| 192 |
+
"<|vision_end|>",
|
| 193 |
+
"<|vision_pad|>",
|
| 194 |
+
"<|image_pad|>",
|
| 195 |
+
"<|video_pad|>"
|
| 196 |
+
],
|
| 197 |
+
"bos_token": null,
|
| 198 |
+
"clean_up_tokenization_spaces": false,
|
| 199 |
+
"eos_token": "<|im_end|>",
|
| 200 |
+
"errors": "replace",
|
| 201 |
+
"extra_special_tokens": {},
|
| 202 |
+
"model_max_length": 131072,
|
| 203 |
+
"pad_token": "<|endoftext|>",
|
| 204 |
+
"processor_class": "Qwen2_5_VLProcessor",
|
| 205 |
+
"split_special_tokens": false,
|
| 206 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 207 |
+
"unk_token": null,
|
| 208 |
+
"use_fast": true
|
| 209 |
+
}
|
video_preprocessor_config.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"crop_size": null,
|
| 3 |
+
"data_format": "channels_first",
|
| 4 |
+
"default_to_square": true,
|
| 5 |
+
"device": null,
|
| 6 |
+
"do_center_crop": null,
|
| 7 |
+
"do_convert_rgb": true,
|
| 8 |
+
"do_normalize": true,
|
| 9 |
+
"do_pad": null,
|
| 10 |
+
"do_rescale": true,
|
| 11 |
+
"do_resize": true,
|
| 12 |
+
"do_sample_frames": false,
|
| 13 |
+
"fps": null,
|
| 14 |
+
"image_mean": [
|
| 15 |
+
0.48145466,
|
| 16 |
+
0.4578275,
|
| 17 |
+
0.40821073
|
| 18 |
+
],
|
| 19 |
+
"image_std": [
|
| 20 |
+
0.26862954,
|
| 21 |
+
0.26130258,
|
| 22 |
+
0.27577711
|
| 23 |
+
],
|
| 24 |
+
"input_data_format": null,
|
| 25 |
+
"max_frames": 768,
|
| 26 |
+
"max_pixels": 3240000,
|
| 27 |
+
"merge_size": 2,
|
| 28 |
+
"min_frames": 4,
|
| 29 |
+
"min_pixels": 3136,
|
| 30 |
+
"num_frames": null,
|
| 31 |
+
"patch_size": 14,
|
| 32 |
+
"processor_class": "Qwen2_5_VLProcessor",
|
| 33 |
+
"resample": 3,
|
| 34 |
+
"rescale_factor": 0.00392156862745098,
|
| 35 |
+
"return_metadata": false,
|
| 36 |
+
"size": {
|
| 37 |
+
"longest_edge": 3240000,
|
| 38 |
+
"shortest_edge": 3136
|
| 39 |
+
},
|
| 40 |
+
"size_divisor": null,
|
| 41 |
+
"temporal_patch_size": 1,
|
| 42 |
+
"video_metadata": null,
|
| 43 |
+
"video_processor_type": "Qwen2VLVideoProcessor"
|
| 44 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|