code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _check_and_set(self, cls_value, sd_value, name):
"""Auxiliary function for checking the values in the checkpoint and
setting them."""
if self.override_opt_param_scheduler:
self.log_rank_0(" > overriding {} value to {}".format(name, cls_value))
return cls_value
... | Auxiliary function for checking the values in the checkpoint and
setting them. | _check_and_set | python | inclusionAI/AReaL | realhf/impl/model/backend/thirdparty/megatron/v0_6_0/lr_schduler.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/backend/thirdparty/megatron/v0_6_0/lr_schduler.py | Apache-2.0 |
def maybe_set_triton_cache_manager() -> None:
"""Set environment variable to tell Triton to use a custom cache
manager."""
cache_manger = os.environ.get("TRITON_CACHE_MANAGER", None)
if cache_manger is None and triton_available:
manager = "realhf.impl.model.backend.thirdparty.vllm.custom_cache_m... | Set environment variable to tell Triton to use a custom cache
manager. | maybe_set_triton_cache_manager | python | inclusionAI/AReaL | realhf/impl/model/backend/thirdparty/vllm/custom_cache_manager.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/backend/thirdparty/vllm/custom_cache_manager.py | Apache-2.0 |
def _assign_src_to_dsts(
node2srcs: Dict[int, List[int]], node2dsts: Dict[int, List[int]]
) -> Dict[int, List[int]]:
"""Assign nodes with a greedy algorithm.
All ranks in the values of node2srcs have the data required by all dst ranks.
Source ranks can be assigned to zero or multiple destination ranks.... | Assign nodes with a greedy algorithm.
All ranks in the values of node2srcs have the data required by all dst ranks.
Source ranks can be assigned to zero or multiple destination ranks.
All destination ranks must be assigned to exactly one src rank.
Args:
node2srcs (Dict[int, List[int]]): Node i... | _assign_src_to_dsts | python | inclusionAI/AReaL | realhf/impl/model/comm/param_realloc.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/comm/param_realloc.py | Apache-2.0 |
def _ppo_actor_loss_from_model_outputs(
logits: torch.FloatTensor, # [tot_seqlen, vocab_size]
input_: SequenceSample,
kl_adapter: ppo_functional.KLController, # const
eps_clip: float, # const
c_clip: float | None,
behav_imp_weight_cap: float | None,
early_stop_imp_ratio: Optional[float], ... | Loss function for ppo actor step, all inputs should be splitted into
pipeline micro batches, returns loss and logging stats. | _ppo_actor_loss_from_model_outputs | python | inclusionAI/AReaL | realhf/impl/model/interface/ppo_interface.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/interface/ppo_interface.py | Apache-2.0 |
def splited_sum_bool_tensor(t: torch.BoolTensor, chunk_size=256 * 1024 * 1024) -> int:
"""Sum a boolean tensor by splitting them into chunks and sum the chunks
separately.
to avoid memory overhead introduced by torch default sum method
(which will apply for a block of memory of size `8 * t.numel()`
... | Sum a boolean tensor by splitting them into chunks and sum the chunks
separately.
to avoid memory overhead introduced by torch default sum method
(which will apply for a block of memory of size `8 * t.numel()`
bytes.)
| splited_sum_bool_tensor | python | inclusionAI/AReaL | realhf/impl/model/interface/ppo_interface.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/interface/ppo_interface.py | Apache-2.0 |
def bias_gelu_back(g, y, bias):
"""Assume that y has shape (B, D) and bias has shape (D)"""
x = bias + y
tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
# sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
ff = 0.5 * x * (
(1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)... | Assume that y has shape (B, D) and bias has shape (D) | bias_gelu_back | python | inclusionAI/AReaL | realhf/impl/model/modules/activations.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/activations.py | Apache-2.0 |
def new_gelu_activation(input: torch.Tensor) -> torch.Tensor:
"""Implementation of the GELU activation function currently in Google BERT
repo (identical to OpenAI GPT).
Also see
the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
"""
return (
0.5
* input
... | Implementation of the GELU activation function currently in Google BERT
repo (identical to OpenAI GPT).
Also see
the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
| new_gelu_activation | python | inclusionAI/AReaL | realhf/impl/model/modules/activations.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/activations.py | Apache-2.0 |
def apply_rotary_emb(
x,
cos,
sin,
interleaved=False,
inplace=False,
seqlen_offsets: Union[int, torch.Tensor] = 0,
cu_seqlens: Optional[torch.Tensor] = None,
max_seqlen: Optional[int] = None,
):
"""
Arguments:
x: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None... |
Arguments:
x: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None
else (total_seqlen, nheads, headdim)
cos, sin: (seqlen_rotary, rotary_dim / 2)
interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
of 1st half and 2nd half (GPT-... | apply_rotary_emb | python | inclusionAI/AReaL | realhf/impl/model/modules/rotary.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/rotary.py | Apache-2.0 |
def forward(
self,
qk: torch.Tensor,
cu_seqlens: Optional[torch.Tensor] = None,
max_seqlen: Optional[int] = None,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""
qkv: (batch, seqlen, nq + nkv, headdim),
seqlen_offset: (batch_size,) or int. Eac... |
qkv: (batch, seqlen, nq + nkv, headdim),
seqlen_offset: (batch_size,) or int. Each sequence in x is shifted by this amount.
Most commonly used in inference when we have KV cache.
If it's a tensor of shape (batch_size,), then to update the cos / sin cache, one
should ... | forward | python | inclusionAI/AReaL | realhf/impl/model/modules/rotary.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/rotary.py | Apache-2.0 |
def sinkhorn_load_balancing(self, logits: torch.Tensor):
"""Apply sinkhorn routing to the logits tensor."""
def _sinkhorn_activation(logits):
if self.config.moe.top_k == 1:
logits = torch.sigmoid(logits)
else: # k > 1
logits = torch.softmax(logit... | Apply sinkhorn routing to the logits tensor. | sinkhorn_load_balancing | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/router.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/router.py | Apache-2.0 |
def aux_loss_load_balancing(self, logits: torch.Tensor):
"""Apply loss-based load balancing to the logits tensor.
Args:
logits (torch.Tensor): the logits tensor after gating, shape: [num_tokens, num_experts].
Returns:
probs (torch.Tensor): the probabilities tensor after... | Apply loss-based load balancing to the logits tensor.
Args:
logits (torch.Tensor): the logits tensor after gating, shape: [num_tokens, num_experts].
Returns:
probs (torch.Tensor): the probabilities tensor after load balancing.
indices (torch.Tensor): the indices ten... | aux_loss_load_balancing | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/router.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/router.py | Apache-2.0 |
def apply_load_balancing_loss(
self,
probs: torch.Tensor,
num_local_tokens_per_expert: torch.Tensor,
activation: torch.Tensor,
):
"""Applies auxiliary loss to the MoE layer.
Args:
probs (torch.Tensor): The probs output by the router for each token. [num_t... | Applies auxiliary loss to the MoE layer.
Args:
probs (torch.Tensor): The probs output by the router for each token. [num_tokens, num_experts]
num_local_tokens_per_expert (torch.Tensor): The number of tokens per expert. [num_experts]
activation (torch.Tensor): The activation ... | apply_load_balancing_loss | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/router.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/router.py | Apache-2.0 |
def apply_z_loss(self, logits):
"""Encourages the router's logits to remain small to enhance stability.
Please refer to the ST-MoE paper (https://arxiv.org/pdf/2202.08906.pdf) for details.
Args:
logits (torch.Tensor): The logits of the router.
Returns:
torch.Ten... | Encourages the router's logits to remain small to enhance stability.
Please refer to the ST-MoE paper (https://arxiv.org/pdf/2202.08906.pdf) for details.
Args:
logits (torch.Tensor): The logits of the router.
Returns:
torch.Tensor: The logits after applying the z-loss.
... | apply_z_loss | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/router.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/router.py | Apache-2.0 |
def apply_input_jitter(self, input: torch.Tensor):
"""Add noise to the input tensor.
Refer to https://arxiv.org/abs/2101.03961.
Args:
input (Tensor): Input tensor.
Returns:
Tensor: Jittered input.
"""
if self.config.moe.input_jitter_eps is not No... | Add noise to the input tensor.
Refer to https://arxiv.org/abs/2101.03961.
Args:
input (Tensor): Input tensor.
Returns:
Tensor: Jittered input.
| apply_input_jitter | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/router.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/router.py | Apache-2.0 |
def routing(self, logits: torch.Tensor):
"""Top-k routing function.
Args:
logits (torch.Tensor): Logits tensor after gating.
Returns:
probs (torch.Tensor): the probabilities tensor after load balancing.
indices (torch.Tensor): the indices tensor after top-k ... | Top-k routing function.
Args:
logits (torch.Tensor): Logits tensor after gating.
Returns:
probs (torch.Tensor): the probabilities tensor after load balancing.
indices (torch.Tensor): the indices tensor after top-k selection.
| routing | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/router.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/router.py | Apache-2.0 |
def forward(self, input: torch.Tensor):
"""Forward pass of the router.
Args:
input (torch.Tensor): Input tensor.
"""
# Apply input jitter
input = self.apply_input_jitter(input)
logits = self.gating(input)
logits = logits.view(-1, self.num_experts)
... | Forward pass of the router.
Args:
input (torch.Tensor): Input tensor.
| forward | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/router.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/router.py | Apache-2.0 |
def __init__(
self,
config: ReaLModelConfig,
dtype: Optional[torch.dtype] = None,
device: Optional[Union[str, torch.device]] = None,
) -> None:
"""Initialize the AlltoAll token dispatcher. Currently does not support
expert parallel.
Args:
num_loca... | Initialize the AlltoAll token dispatcher. Currently does not support
expert parallel.
Args:
num_local_experts (int): Number of local experts on the current device.
config (TransformerConfig): Configuration for the transformer model.
| __init__ | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/token_dispatcher.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/token_dispatcher.py | Apache-2.0 |
def preprocess(self, indices: torch.Tensor) -> torch.Tensor:
"""Preprocess token indices for AlltoAll communication and token
permutation. This method computes the number of tokens assigned to each
expert based on the input indices. It also initializes the necessary
data structures for A... | Preprocess token indices for AlltoAll communication and token
permutation. This method computes the number of tokens assigned to each
expert based on the input indices. It also initializes the necessary
data structures for AlltoAll communication, such as input and output
splits, and the ... | preprocess | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/token_dispatcher.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/token_dispatcher.py | Apache-2.0 |
def token_permutation(
self,
hidden_states: torch.Tensor,
probs: torch.Tensor,
indices: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Dispatch tokens to local experts using AlltoAll communication.
Args:
hidden_states (torch.Tensor): Input token... | Dispatch tokens to local experts using AlltoAll communication.
Args:
hidden_states (torch.Tensor): Input token embeddings.
probs (torch.Tensor): Probs of tokens assigned to experts.
indices (torch.Tensor): Indices of tokens assigned to experts.
Returns:
... | token_permutation | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/token_dispatcher.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/token_dispatcher.py | Apache-2.0 |
def token_unpermutation(
self,
hidden_states: torch.Tensor,
) -> torch.Tensor:
"""Reverse the token permutation to restore the original order.
Args:
hidden_states (torch.Tensor): Output from local experts.
bias (torch.Tensor, optional): Bias tensor (not suppo... | Reverse the token permutation to restore the original order.
Args:
hidden_states (torch.Tensor): Output from local experts.
bias (torch.Tensor, optional): Bias tensor (not supported).
Returns:
Tuple[torch.Tensor, Optional[torch.Tensor]]:
- Unpermuted... | token_unpermutation | python | inclusionAI/AReaL | realhf/impl/model/modules/moe/token_dispatcher.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/modules/moe/token_dispatcher.py | Apache-2.0 |
def instantiate(self):
"""Instantiate the model parameters.
Note that users can append hooks to this method to do more
processing, such as loading from HuggingFace models.
"""
assert not self._instantiated or self.contiguous_param.numel() == 0
layers = []
for idx... | Instantiate the model parameters.
Note that users can append hooks to this method to do more
processing, such as loading from HuggingFace models.
| instantiate | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_api.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_api.py | Apache-2.0 |
def state_dict(self, *args, **kwargs):
"""Map layer indices to global layer indices."""
state_dict = self.layers.state_dict(*args, **kwargs)
new_state_dict = {}
for k, v in state_dict.items():
k = k.lstrip("module.").lstrip("layers.")
local_idx = int(k.split(".")[... | Map layer indices to global layer indices. | state_dict | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_api.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_api.py | Apache-2.0 |
def build_reparallelized_layers_async(
self,
from_model_name: ModelName,
to_model_name: ModelName,
from_topo: topology.ProcessTopology,
to_topo: topology.ProcessTopology,
to_model_config: model_api.ReaLModelConfig,
pg_info: NCCLProcessGroupInfo,
) -> Tuple[nn.... | Trigger the parameter realloaction from the source model to the
target model. | build_reparallelized_layers_async | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_api.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_api.py | Apache-2.0 |
def genstep(
next_token_logits: torch.Tensor,
tokenizer: transformers.PreTrainedTokenizerFast,
unfinished_sequences: torch.Tensor,
generated_idx: Union[torch.IntTensor, int],
gconfig: GenerationHyperparameters,
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor], bool, torch.Tensor]:
"... | Advance generation by one step given logits.
Args:
next_token_logits (torch.Tensor): Shape [bs, vocab_size].
tokenizer (transformers.PreTrainedTokenizerFast): .
unfinished_sequences (torch.Tensor): Bool tensor indicator of whether a sequence is finished.
Shape [bs].
gene... | genstep | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_generate.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_generate.py | Apache-2.0 |
def _gather_gen_output_from_list(
gen_token_ph: List[torch.LongTensor],
gen_logprob_ph: List[torch.FloatTensor],
gen_logits_mask_ph: List[torch.BoolTensor],
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Stack over the sequence dimension given a list of single-token
tensors."""
gen_tok... | Stack over the sequence dimension given a list of single-token
tensors. | _gather_gen_output_from_list | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_generate.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_generate.py | Apache-2.0 |
def _gather_minibatch_gen_outputs(
all_gen_tokens: List[torch.LongTensor],
all_log_probs: List[torch.FloatTensor],
all_logits_mask: List[torch.BoolTensor],
pad_token_id: int,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Concate over the batch dimension given multiple [bs, seqlen] mini-ba... | Concate over the batch dimension given multiple [bs, seqlen] mini-batch
tensors.
Since different minibatches may have different generated lengths, we
should pad them to the same length.
| _gather_minibatch_gen_outputs | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_generate.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_generate.py | Apache-2.0 |
def tensor_slice_partition_fn(
tensor: torch.Tensor,
tp_rank: Optional[int],
tp_world_size: int,
dim: Optional[int],
) -> Union[List[torch.Tensor], torch.Tensor]:
"""Partition a tensor by slicing along a dimension for tensor-model
parallelism."""
if dim is None:
splits = [tensor for ... | Partition a tensor by slicing along a dimension for tensor-model
parallelism. | tensor_slice_partition_fn | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_parallel.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_parallel.py | Apache-2.0 |
def intervals_partition_fn(
shape: torch.Size,
tp_rank: Optional[int],
tp_world_size: int,
dim: Optional[int],
) -> Union[List[torch.Tensor], torch.Tensor]:
"""Get the intervals of a MP-partitioned tensor in the flatten view.
For example, if a tensor of shape (2, 4) is partitioned along the
... | Get the intervals of a MP-partitioned tensor in the flatten view.
For example, if a tensor of shape (2, 4) is partitioned along the
second dimension into 2 parts, then the intervals of the first part
are [(0, 2), (2, 4)].
Used by parameter reallocation. Return a numpy array of shape [N,
2], where ... | intervals_partition_fn | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_parallel.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_parallel.py | Apache-2.0 |
def shape_partition_fn(
shape: torch.Size,
tp_rank: Optional[int],
tp_world_size: int,
dim: Optional[int],
):
"""Get the partitioned shape of a tensor for tensor-model parallelism."""
if dim is None:
splits = [shape for _ in range(tp_world_size)]
else:
if dim < 0:
... | Get the partitioned shape of a tensor for tensor-model parallelism. | shape_partition_fn | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_parallel.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_parallel.py | Apache-2.0 |
def tp_partition_key(
key: str,
tensor_or_shape: torch.Tensor | torch.Size,
tp_rank: Optional[int],
tp_size: Optional[int],
config: model_api.ReaLModelConfig,
partition_fn: Callable[
[torch.Tensor, Optional[int], int, Optional[int]],
Union[List[torch.Tensor], torch.Tensor],
]... | Run the partition functor on the tensor or shape based on the key.
The key determines the partitioning strategy, e.g., whether to
perform partition and along which dimension.
| tp_partition_key | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_parallel.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_parallel.py | Apache-2.0 |
def tp_partition_real_model_state_dict(
state_dict: Dict[str, torch.Tensor],
config: model_api.ReaLModelConfig,
tp_size: int,
tp_rank: Optional[int] = None,
) -> Union[Dict, List[Dict]]:
"""A helper function to partition a state dict using `tp_partition_key`."""
if tp_size == 1:
if tp_ra... | A helper function to partition a state dict using `tp_partition_key`. | tp_partition_real_model_state_dict | python | inclusionAI/AReaL | realhf/impl/model/nn/real_llm_parallel.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/nn/real_llm_parallel.py | Apache-2.0 |
def _buffer_idx(self, micro_batch_id):
"""Map a micro-batch index to a pipeline buffer index.
This method uses a cyclic allocation strategy.
Args:
micro_batch_id (int): The micro-batch index relative to the beginning of the schedule.
Returns:
int: The index of ... | Map a micro-batch index to a pipeline buffer index.
This method uses a cyclic allocation strategy.
Args:
micro_batch_id (int): The micro-batch index relative to the beginning of the schedule.
Returns:
int: The index of the buffer that should store data.
| _buffer_idx | python | inclusionAI/AReaL | realhf/impl/model/parallelism/pipeline_parallel/static_schedule.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/pipeline_parallel/static_schedule.py | Apache-2.0 |
def num_pipe_buffers(self):
"""Return the number of pipeline buffers required for this stage.
This is equivalent to the maximum number of in-flight forward
passes, since we need to remember the activations of forward
passes in order to run backpropagation. For synchronous 1F1B,
... | Return the number of pipeline buffers required for this stage.
This is equivalent to the maximum number of in-flight forward
passes, since we need to remember the activations of forward
passes in order to run backpropagation. For synchronous 1F1B,
this is equivalent to the index differe... | num_pipe_buffers | python | inclusionAI/AReaL | realhf/impl/model/parallelism/pipeline_parallel/static_schedule.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/pipeline_parallel/static_schedule.py | Apache-2.0 |
def _reduce(input_):
"""All-reduce the input tensor across model parallel group."""
# Bypass the function if we are using only 1 GPU.
if constants.tensor_parallel_world_size() == 1:
return input_
# All-reduce.
torch.distributed.all_reduce(input_, group=constants.tensor_parallel_group())
... | All-reduce the input tensor across model parallel group. | _reduce | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/mappings.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/mappings.py | Apache-2.0 |
def _split_along_last_dim(input_):
"""Split the tensor along its last dimension and keep the corresponding
slice."""
world_size = constants.tensor_parallel_world_size()
# Bypass the function if we are using only 1 GPU.
if world_size == 1:
return input_
# Split along last dimension.
... | Split the tensor along its last dimension and keep the corresponding
slice. | _split_along_last_dim | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/mappings.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/mappings.py | Apache-2.0 |
def _split_along_first_dim(input_):
"""Split the tensor along its first dimension and keep the corresponding
slice."""
world_size = constants.tensor_parallel_world_size()
# Bypass the function if we are using only 1 GPU.
if world_size == 1:
return input_
# Split along first dimension.
... | Split the tensor along its first dimension and keep the corresponding
slice. | _split_along_first_dim | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/mappings.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/mappings.py | Apache-2.0 |
def _gather_along_first_dim(input_):
"""Gather tensors and concatinate along the first dimension."""
world_size = constants.tensor_parallel_world_size()
# Bypass the function if we are using only 1 GPU.
if world_size == 1:
return input_
dim_size = list(input_.size())
dim_size[0] = dim_... | Gather tensors and concatinate along the first dimension. | _gather_along_first_dim | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/mappings.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/mappings.py | Apache-2.0 |
def _reduce_scatter_along_first_dim(input_):
"""Reduce-scatter the input tensor across model parallel group."""
world_size = constants.tensor_parallel_world_size()
# Bypass the function if we are using only 1 GPU.
if world_size == 1:
return input_
dim_size = list(input_.size())
assert (... | Reduce-scatter the input tensor across model parallel group. | _reduce_scatter_along_first_dim | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/mappings.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/mappings.py | Apache-2.0 |
def linear_with_frozen_weight(
input: torch.Tensor,
weight: torch.Tensor,
bias: Optional[torch.Tensor],
gradient_accumulation_fusion: bool,
async_grad_allreduce: bool,
sequence_parallel: bool,
) -> torch.Tensor:
"""Linear layer execution with weight.requires_grad == False.
This function... | Linear layer execution with weight.requires_grad == False.
This function handles linear layers with weight frozen (untrainable).
In the forward, it only saves weight and does not save input activations.
In the backward, it does not perform weight gradient calculation, or
weight gradient allreduce.
... | linear_with_frozen_weight | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/modules.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/modules.py | Apache-2.0 |
def linear_with_grad_accumulation_and_async_allreduce(
input: torch.Tensor,
weight: torch.Tensor,
bias: Optional[torch.Tensor],
gradient_accumulation_fusion: bool,
async_grad_allreduce: bool,
sequence_parallel: bool,
) -> torch.Tensor:
"""Linear layer execution with asynchronous communicatio... | Linear layer execution with asynchronous communication and gradient
accumulation fusion in backprop.
This has the option to accumulate the result of backprop
calculation into an existing gradient buffer, preventing the need
to do an additional addition kernel after the gradient
calculation.
Ad... | linear_with_grad_accumulation_and_async_allreduce | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/modules.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/modules.py | Apache-2.0 |
def merged_linear_with_grad_accumulation_and_async_allreduce(
input: torch.Tensor,
gradient_accumulation_fusion: bool,
async_grad_allreduce: bool,
sequence_parallel: bool,
is_w_parallel: List[bool],
*wbs: List[torch.Tensor | None],
) -> torch.Tensor:
"""Similar to linear_with_grad_accumulati... | Similar to linear_with_grad_accumulation_and_async_allreduce but does
multiple linear-layer forward/backward calls with a single all gather
operation. | merged_linear_with_grad_accumulation_and_async_allreduce | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/modules.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/modules.py | Apache-2.0 |
def forward(self, input_) -> torch.Tensor:
"""Forward of ColumnParallelLinear.
Args:
input_: 3D tensor whose order of dimension is [sequence, batch, hidden]
Returns:
- output
- bias
"""
bias = self.bias if not self.skip_bias_add else None
... | Forward of ColumnParallelLinear.
Args:
input_: 3D tensor whose order of dimension is [sequence, batch, hidden]
Returns:
- output
- bias
| forward | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/modules.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/modules.py | Apache-2.0 |
def forward(self, input_) -> torch.Tensor:
"""Forward of RowParallelLinear.
Args:
input_: 3D tensor whose order of dimension is [sequence, batch, hidden]
Returns:
- output
- bias
"""
# NOTE: ColumnParallelLinear and RowParallelLinear in exper... | Forward of RowParallelLinear.
Args:
input_: 3D tensor whose order of dimension is [sequence, batch, hidden]
Returns:
- output
- bias
| forward | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/modules.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/modules.py | Apache-2.0 |
def parallel_lm_logits(
input_: torch.HalfTensor,
word_embeddings_weight: torch.HalfTensor,
parallel_output: bool = False,
gradient_accumulation_fusion: bool = False,
bias=None,
):
"""LM logits using word embedding weights."""
tensor_parallel = constants.tensor_parallel_world_size() > 1
... | LM logits using word embedding weights. | parallel_lm_logits | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/modules.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/modules.py | Apache-2.0 |
def vocab_parallel_cross_entropy(vocab_parallel_logits, target, label_smoothing=0.0):
"""Performs cross entropy loss when logits are split across tensor parallel
ranks.
Arguments:
vocab_parallel_logits: logits split across tensor parallel ranks
dimension is [sequence_... | Performs cross entropy loss when logits are split across tensor parallel
ranks.
Arguments:
vocab_parallel_logits: logits split across tensor parallel ranks
dimension is [sequence_length, batch_size, hidden_size]
target: correct vocab ids of dimseion [sequence_len... | vocab_parallel_cross_entropy | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/modules.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/modules.py | Apache-2.0 |
def ensure_divisibility(numerator, denominator):
"""Ensure that numerator is divisible by the denominator."""
assert numerator % denominator == 0, "{} is not divisible by {}".format(
numerator, denominator
) | Ensure that numerator is divisible by the denominator. | ensure_divisibility | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/utils.py | Apache-2.0 |
def divide(numerator, denominator):
"""Ensure that numerator is divisible by the denominator and return the
division value."""
ensure_divisibility(numerator, denominator)
return numerator // denominator | Ensure that numerator is divisible by the denominator and return the
division value. | divide | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/utils.py | Apache-2.0 |
def split_tensor_along_last_dim(
tensor: torch.Tensor,
num_partitions: int,
contiguous_split_chunks: bool = False,
) -> List[torch.Tensor]:
"""Split a tensor along its last dimension.
Arguments:
tensor: input tensor.
num_partitions: number of partitions to split the tensor
c... | Split a tensor along its last dimension.
Arguments:
tensor: input tensor.
num_partitions: number of partitions to split the tensor
contiguous_split_chunks: If True, make each chunk contiguous
in memory.
Returns:
A list of Tensors
| split_tensor_along_last_dim | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/utils.py | Apache-2.0 |
def split_tensor_into_1d_equal_chunks(tensor, new_buffer=False):
"""Break a tensor into equal 1D chunks across tensor parallel ranks.
Returns a Tensor or View with this rank's portion of the data.
Arguments:
tensor: The tensor to split
Keyword Arguments:
new_buffer (bool): If True, re... | Break a tensor into equal 1D chunks across tensor parallel ranks.
Returns a Tensor or View with this rank's portion of the data.
Arguments:
tensor: The tensor to split
Keyword Arguments:
new_buffer (bool): If True, returns a new Tensor.
If False, returns a view ... | split_tensor_into_1d_equal_chunks | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/utils.py | Apache-2.0 |
def gather_split_1d_tensor(tensor):
"""Opposite of split_tensor_into_1d_equal_chunks. Gather values from tensor
model parallel ranks.
Returns a new Tensor with the gathered data.
Arguments:
tensor: A Tensor or view of this rank's portion of the data.
"""
numel_gathered = torch.numel(te... | Opposite of split_tensor_into_1d_equal_chunks. Gather values from tensor
model parallel ranks.
Returns a new Tensor with the gathered data.
Arguments:
tensor: A Tensor or view of this rank's portion of the data.
| gather_split_1d_tensor | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/utils.py | Apache-2.0 |
def assert_viewless_tensor(tensor, extra_msg=None):
"""Assert that a tensor is not a view (i.e., its '._base' field is not
set)."""
if isinstance(tensor, list):
[assert_viewless_tensor(t) for t in tensor]
return tensor
if not isinstance(tensor, torch.Tensor):
return tensor
as... | Assert that a tensor is not a view (i.e., its '._base' field is not
set). | assert_viewless_tensor | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/utils.py | Apache-2.0 |
def safely_set_viewless_tensor_data(tensor, new_data_tensor):
"""Safely set tensor's '.data' field.
Check first that the tensor is viewless (i.e., '._base' not set). If
not, raise an exception.
"""
assert_viewless_tensor(
tensor,
extra_msg="FYI, tensor._base has shape %s, and new_da... | Safely set tensor's '.data' field.
Check first that the tensor is viewless (i.e., '._base' not set). If
not, raise an exception.
| safely_set_viewless_tensor_data | python | inclusionAI/AReaL | realhf/impl/model/parallelism/tensor_parallel/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/parallelism/tensor_parallel/utils.py | Apache-2.0 |
def outer_capture_context(stream=None, no_grad=False):
"""Context wrapped outside warmup and CUDAGraph capture context:
1. Alter stream from default.
2. Apply torch.no_grad context if required
"""
if stream is None:
stream = torch.cuda.Stream()
maybe_no_grad = nullcontext() if not no_gra... | Context wrapped outside warmup and CUDAGraph capture context:
1. Alter stream from default.
2. Apply torch.no_grad context if required
| outer_capture_context | python | inclusionAI/AReaL | realhf/impl/model/utils/cuda_graph.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/cuda_graph.py | Apache-2.0 |
def capture_func(
name: str,
func: Callable,
input_buffer: Dict[str, Any],
force_recapture: bool = False,
no_grad: bool = False,
) -> Tuple[Any, Dict[str, torch.Tensor], Dict[str, torch.Tensor]]:
"""Capture a function with cuda graph, store the graph and input/output
buffers by name. The inp... | Capture a function with cuda graph, store the graph and input/output
buffers by name. The input/output metadata should match the inputs and
outputs of function.
This function uses pytorch original CUDAGraph implementation
:param name: The identifier of the CUDAGraph to be captured/reused.
:type na... | capture_func | python | inclusionAI/AReaL | realhf/impl/model/utils/cuda_graph.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/cuda_graph.py | Apache-2.0 |
def gather_shifted_log_probs(
logits: torch.FloatTensor, labels: torch.LongTensor
) -> torch.FloatTensor:
"""Gather log probs of shifted labels from logits.
Args:
logits (torch.FloatTensor): Non-shifted logits with shape [bs, seqlen].
The final value at [:, seqlen -1] is not used.
... | Gather log probs of shifted labels from logits.
Args:
logits (torch.FloatTensor): Non-shifted logits with shape [bs, seqlen].
The final value at [:, seqlen -1] is not used.
labels (torch.LongTensor): Non-shifted labels/input_ids with shape [bs, seqlen].
The first value at [:... | gather_shifted_log_probs | python | inclusionAI/AReaL | realhf/impl/model/utils/functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/functional.py | Apache-2.0 |
def build_shift_one_indices(
x: torch.HalfTensor, cu_seqlens: torch.IntTensor
) -> torch.IntTensor:
"""Build indices for shifting labels/input_ids one step to the left.
Equivalent to:
```
shift_one_indices = torch.cat([
torch.arange(cu_seqlens[i] + 1, cu_seqlens[i + 1], dtype=torch.long, de... | Build indices for shifting labels/input_ids one step to the left.
Equivalent to:
```
shift_one_indices = torch.cat([
torch.arange(cu_seqlens[i] + 1, cu_seqlens[i + 1], dtype=torch.long, device=cu_seqlens.device)
for i in range(cu_seqlens.shape[0] - 1)
])
```
but the above implem... | build_shift_one_indices | python | inclusionAI/AReaL | realhf/impl/model/utils/functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/functional.py | Apache-2.0 |
def build_leave_one_indices(
x: torch.HalfTensor, cu_seqlens: torch.IntTensor
) -> torch.IntTensor:
"""Build indices for leaving one token out at the end of each sequence.
Equivalent to:
```
leave_one_indices = torch.cat([
torch.arange(cu_seqlens[i], cu_seqlens[i + 1] - 1, dtype=torch.long,... | Build indices for leaving one token out at the end of each sequence.
Equivalent to:
```
leave_one_indices = torch.cat([
torch.arange(cu_seqlens[i], cu_seqlens[i + 1] - 1, dtype=torch.long, device=cu_seqlens.device)
for i in range(cu_seqlens.shape[0] - 1)
])
```
but the above imp... | build_leave_one_indices | python | inclusionAI/AReaL | realhf/impl/model/utils/functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/functional.py | Apache-2.0 |
def _gather_logprobs(
logits: torch.Tensor,
labels: torch.Tensor,
):
"""Gather log probs from logits and labels.
Args:
logits (torch.FloatTensor): Shape [tot_seqlen]. The final value at the end of
each sequence is not used.
labels (torch.LongTensor): Labels or input_ids with... | Gather log probs from logits and labels.
Args:
logits (torch.FloatTensor): Shape [tot_seqlen]. The final value at the end of
each sequence is not used.
labels (torch.LongTensor): Labels or input_ids with shape [tot_seqlen].
The first value at the beginning of each sequence h... | _gather_logprobs | python | inclusionAI/AReaL | realhf/impl/model/utils/functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/functional.py | Apache-2.0 |
def gather_packed_shifted_log_probs(
logits: torch.FloatTensor,
cu_seqlens: torch.Tensor,
labels: torch.LongTensor,
) -> torch.FloatTensor:
"""Gather log probs from packed input_ids and logits.
Args:
logits (torch.FloatTensor): Shape [tot_seqlen]. The final value at the end of
e... | Gather log probs from packed input_ids and logits.
Args:
logits (torch.FloatTensor): Shape [tot_seqlen]. The final value at the end of
each sequence is not used.
cu_seqlens (torch.Tensor): Shape [#seqs + 1]. Indices marking the start
and end of each sequence.
labels ... | gather_packed_shifted_log_probs | python | inclusionAI/AReaL | realhf/impl/model/utils/functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/functional.py | Apache-2.0 |
def masked_normalization(
x: torch.Tensor,
mask: Optional[torch.BoolTensor] = None,
dim=None,
inplace=False,
unbiased=False,
eps=1e-5,
high_precision=True,
all_reduce=True,
):
"""Normalize x with a mask. Typically used in advantage normalization.
Args:
x (torch.Tensor):
... | Normalize x with a mask. Typically used in advantage normalization.
Args:
x (torch.Tensor):
Tensor to be normalized.
mask (torch.Tensor, optional):
A mask with the same shape as x. Defaults to None.
dim (int or tuple of ints, optional):
Dimensions to be n... | masked_normalization | python | inclusionAI/AReaL | realhf/impl/model/utils/functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/functional.py | Apache-2.0 |
def torch_attn_func(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
causal: bool,
cu_seqlens_q: torch.IntTensor,
max_seqlen_q: int,
cu_seqlens_k: torch.IntTensor,
max_seqlen_k: int,
dropout_p: float,
softmax_scale: float,
upcast_unscale: float = 1.0,
) -> torch.Tensor:
... | PyTorch implementation of the attention function with a flash-attn-like
realhf.api.
We use this function to compare the output of our model and huggingface models.
Flash-attn/float16/CUDAkernels will all more or less suffer from float point errors.
We call this function with float32 and CPU to get the ... | torch_attn_func | python | inclusionAI/AReaL | realhf/impl/model/utils/functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/functional.py | Apache-2.0 |
def apply_rotary(
x: torch.HalfTensor,
cos: torch.HalfTensor,
sin: torch.HalfTensor,
interleaved: bool = False,
):
"""
x: (batch_size, seqlen, nheads, headdim)
cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2)
"""
ro_dim = cos.shape[-1] * 2
assert ro_dim ... |
x: (batch_size, seqlen, nheads, headdim)
cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2)
| apply_rotary | python | inclusionAI/AReaL | realhf/impl/model/utils/functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/functional.py | Apache-2.0 |
def switch_load_balancing_loss_func(
probs: torch.Tensor,
tokens_per_expert: torch.Tensor,
topk: int,
moe_aux_loss_coeff: float,
sequence_partition_group=None,
):
"""Calculate the auxiliary loss for load balancing.
Refer to the Switch Transformer paper (https://arxiv.org/abs/2101.03961) for ... | Calculate the auxiliary loss for load balancing.
Refer to the Switch Transformer paper (https://arxiv.org/abs/2101.03961) for details.
Args:
probs (torch.Tensor): Softmax probabilities output by the router for each token. [num_tokens, num_experts]
tokens_per_expert (torch.Tensor): Number of tok... | switch_load_balancing_loss_func | python | inclusionAI/AReaL | realhf/impl/model/utils/moe.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/moe.py | Apache-2.0 |
def get_capacity(
num_tokens: int, num_experts: int, capacity_factor: float, min_capacity=None
):
"""Calculate the capacity of each expert.
Args:
num_tokens (int): num of the input tokens.
num_experts (int): num of the experts.
capacity_factor (float): Capacity factor.
min_c... | Calculate the capacity of each expert.
Args:
num_tokens (int): num of the input tokens.
num_experts (int): num of the experts.
capacity_factor (float): Capacity factor.
min_capacity (int, optional): Minimum capacity. Defaults to None.
Returns:
Tensor: Capacity of each e... | get_capacity | python | inclusionAI/AReaL | realhf/impl/model/utils/moe.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/moe.py | Apache-2.0 |
def custom_histc(input: torch.Tensor, bins: int, min: Any, max: Any):
"""A CPU compatible version of torch.histc."""
if input.is_cpu:
out = torch.zeros(bins, dtype=torch.long)
bin_width = (max - min) / bins
# Iterate over the input tensor and increment the appropriate bin
for va... | A CPU compatible version of torch.histc. | custom_histc | python | inclusionAI/AReaL | realhf/impl/model/utils/moe.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/moe.py | Apache-2.0 |
def backward(ctx, grad_output: torch.Tensor):
"""Compute and scale the gradient for auxiliary loss..
Args:
grad_output (torch.Tensor): The gradient of the output.
Returns:
Tuple[torch.Tensor, torch.Tensor]: The gradient of the output, scaled auxiliary loss gradient.
... | Compute and scale the gradient for auxiliary loss..
Args:
grad_output (torch.Tensor): The gradient of the output.
Returns:
Tuple[torch.Tensor, torch.Tensor]: The gradient of the output, scaled auxiliary loss gradient.
| backward | python | inclusionAI/AReaL | realhf/impl/model/utils/moe.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/moe.py | Apache-2.0 |
def permute(tokens, indices, num_out_tokens: int = None, padded_mode: bool = False):
"""Permute the tokens based on the indices. Token with the same index will be grouped together.
The input indices shape is [tokens, top_k], it indicates which experts were selected by each token separately.
Args:
... | Permute the tokens based on the indices. Token with the same index will be grouped together.
The input indices shape is [tokens, top_k], it indicates which experts were selected by each token separately.
Args:
tokens (torch.Tensor): The input token tensor.
indices (torch.Tensor): The token to... | permute | python | inclusionAI/AReaL | realhf/impl/model/utils/moe.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/moe.py | Apache-2.0 |
def unpermute(
permuted_tokens: torch.Tensor,
sorted_indices: torch.Tensor,
probs: torch.Tensor = None,
padded_mode: bool = False,
restore_shape: torch.Size = None,
):
"""Unpermute a tensor of permuted tokens based on sorted indices, and
optionally merge the tokens with their corresponding p... | Unpermute a tensor of permuted tokens based on sorted indices, and
optionally merge the tokens with their corresponding probabilities.
Args:
permuted_tokens (torch.Tensor): The tensor of permuted tokens to be unpermuted.
sorted_indices (torch.Tensor): The tensor of sorted indices used to unperm... | unpermute | python | inclusionAI/AReaL | realhf/impl/model/utils/moe.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/moe.py | Apache-2.0 |
def permute_with_padded_tokens(tokens, indices):
"""Permute the tokens based on the indices, only used in padding mode.
The input indices shape is [num_expert, capacity], it indicates which tokens were selected by each expert separately.
Args:
tokens (torch.Tensor): The input token tensor.
... | Permute the tokens based on the indices, only used in padding mode.
The input indices shape is [num_expert, capacity], it indicates which tokens were selected by each expert separately.
Args:
tokens (torch.Tensor): The input token tensor.
indices (torch.Tensor): A tensor with shape [num_exper... | permute_with_padded_tokens | python | inclusionAI/AReaL | realhf/impl/model/utils/moe.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/moe.py | Apache-2.0 |
def unpermute_with_padded_tokens(
permuted_tokens: torch.Tensor,
indices: torch.Tensor,
probs: torch.Tensor,
restore_shape: torch.Size,
) -> torch.Tensor:
"""Unpermutes a padded permuted tokens based on sorted indices and merges
the tokens with their corresponding probabilities.
This functi... | Unpermutes a padded permuted tokens based on sorted indices and merges
the tokens with their corresponding probabilities.
This function takes a tensor of permuted tokens and reorders them according to the provided indices. It also combines the tokens with their associated probabilities.
Parameters:
... | unpermute_with_padded_tokens | python | inclusionAI/AReaL | realhf/impl/model/utils/moe.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/moe.py | Apache-2.0 |
def topk_softmax_with_capacity(
logits: torch.Tensor,
topk: int,
capacity_factor: Optional[float] = None,
pad_to_capacity: bool = False,
drop_policy: str = "probs",
):
"""Apply capacity and padding to the top-k selection.
Args:
logits (torch.Tensor): Logits tensor.
topk (int)... | Apply capacity and padding to the top-k selection.
Args:
logits (torch.Tensor): Logits tensor.
topk (int): The number of experts to select for each token.
capacity_factor (int): The capacity factor of each expert. Will drop tokens if the number of tokens exceeds the capacity.
pad_to_... | topk_softmax_with_capacity | python | inclusionAI/AReaL | realhf/impl/model/utils/moe.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/moe.py | Apache-2.0 |
def update_aux_losses_tracker(
name: str, loss: torch.Tensor, layer_number: int, num_layers: int
):
"""Save the auxiliary loss for logging.
Args:
name (str): The name of the loss.
loss (torch.Tensor): The loss tensor.
layer_number (int): Layer index of the loss.
num_layers (... | Save the auxiliary loss for logging.
Args:
name (str): The name of the loss.
loss (torch.Tensor): The loss tensor.
layer_number (int): Layer index of the loss.
num_layers (int): The number of total layers.
| update_aux_losses_tracker | python | inclusionAI/AReaL | realhf/impl/model/utils/moe.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/moe.py | Apache-2.0 |
def unpad_input(hidden_states, attention_mask):
"""
Arguments:
hidden_states: (batch, seqlen, ...)
attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
Return:
hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_ma... |
Arguments:
hidden_states: (batch, seqlen, ...)
attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
Return:
hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
cu_seqlens: (batch + 1), the cumulative seq... | unpad_input | python | inclusionAI/AReaL | realhf/impl/model/utils/padding.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/padding.py | Apache-2.0 |
def unpad_input_for_concatenated_sequences(hidden_states, attention_mask_in_length):
"""
Supports concatenating short samples in one sequence.
The attention_mask_in_length is utilized to mask other short samples.
It helps efficient training of variant lengths-based samples
(e.g., the supervised fine... |
Supports concatenating short samples in one sequence.
The attention_mask_in_length is utilized to mask other short samples.
It helps efficient training of variant lengths-based samples
(e.g., the supervised fine-tuning task in large language model).
The motivation for this function is explained
... | unpad_input_for_concatenated_sequences | python | inclusionAI/AReaL | realhf/impl/model/utils/padding.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/padding.py | Apache-2.0 |
def pad_input(hidden_states, indices, batch, seqlen):
"""
Arguments:
hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
indices: (total_nnz)
Return:
hidden_states: (batch, seqlen, ...)
"""
dim = hidden_states.shape[-1]
# out... |
Arguments:
hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
indices: (total_nnz)
Return:
hidden_states: (batch, seqlen, ...)
| pad_input | python | inclusionAI/AReaL | realhf/impl/model/utils/padding.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/padding.py | Apache-2.0 |
def pad_sequence_parallel_input(
packed_input_ids: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int
):
"""Sequence parallel requires packed_input_ids has a shape of 1 dimension
[total_seq_len], and total_seq_len should be divisible by
tensor_parallel_world_size. This function is used to pad packe... | Sequence parallel requires packed_input_ids has a shape of 1 dimension
[total_seq_len], and total_seq_len should be divisible by
tensor_parallel_world_size. This function is used to pad packed_input_ids to
suitable length with an empty sequence, and return new packed_input_ids,
cu_seqlens and max_seqlen... | pad_sequence_parallel_input | python | inclusionAI/AReaL | realhf/impl/model/utils/padding.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/padding.py | Apache-2.0 |
def pad_sequence_parallel_generate_input(
packed_input_ids: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int
):
"""Only for pipeline generate input when model+seq parallel is enabled. To
make sure inputs for seq parallel model have a shape with first dimension
divisible by tensor_parallel_world_s... | Only for pipeline generate input when model+seq parallel is enabled. To
make sure inputs for seq parallel model have a shape with first dimension
divisible by tensor_parallel_world_size, the packed_input_ids should have
length divisible by tensor_parallel_world_size, and contains number of
sequences div... | pad_sequence_parallel_generate_input | python | inclusionAI/AReaL | realhf/impl/model/utils/padding.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/padding.py | Apache-2.0 |
def actor_loss_fn(
logprobs: torch.FloatTensor,
old_logprobs: torch.FloatTensor,
advantages: torch.FloatTensor,
eps_clip: float,
loss_mask: Optional[torch.BoolTensor] = None,
c_clip: Optional[float] = None,
proximal_logprobs: Optional[torch.FloatTensor] = None,
behav_imp_weight_cap: Opti... | Compute PPO actor loss function.
There is no shape requirements for the inputs, but they must have the same shape.
Either [bs, max_seqlen] for batch padded inputs or [tot_seqlen] for padded inputs.
Args:
logprobs (torch.FloatTensor): Log probabilities of actions.
old_logprobs (torch.FloatT... | actor_loss_fn | python | inclusionAI/AReaL | realhf/impl/model/utils/ppo_functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/ppo_functional.py | Apache-2.0 |
def critic_loss_fn(
value: torch.FloatTensor,
old_value: torch.FloatTensor,
target_value: torch.FloatTensor,
value_eps_clip: float,
loss_mask: Optional[torch.FloatTensor] = None,
loss_fn_type: str = "mse",
) -> Tuple[torch.Tensor, Dict]:
"""Compute PPO critic loss function given padded batch... | Compute PPO critic loss function given padded batch inputs.
There is no shape requirements for the inputs, but they must have the same shape.
Either [bs, max_seqlen] for batch padded inputs or [tot_seqlen] for padded inputs.
Args:
value (torch.FloatTensor): Values. The position of the final token ... | critic_loss_fn | python | inclusionAI/AReaL | realhf/impl/model/utils/ppo_functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/ppo_functional.py | Apache-2.0 |
def cugae1d_nolp_misalign_func(
rewards: torch.FloatTensor,
values: torch.FloatTensor,
cu_seqlens: torch.IntTensor,
truncate: torch.BoolTensor,
gamma: float,
lam: float,
) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
"""Compute GAE over a batch of packed sequences with different lengths.
... | Compute GAE over a batch of packed sequences with different lengths.
This function assumes that rewards and values are packed into an 1D tensor.
Values are longer than rewards by the number of sequences in rewards because of bootstrapping.
cu_seqlens marks the bounary of sequences in rewards.
The fina... | cugae1d_nolp_misalign_func | python | inclusionAI/AReaL | realhf/impl/model/utils/ppo_functional.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/ppo_functional.py | Apache-2.0 |
def get_states(self):
"""Get rng states.
Copy the dictionary so we have direct pointers to the states,
not just a pointer to the dictionary.
"""
states = {}
for name in self.states_:
states[name] = self.states_[name]
return states | Get rng states.
Copy the dictionary so we have direct pointers to the states,
not just a pointer to the dictionary.
| get_states | python | inclusionAI/AReaL | realhf/impl/model/utils/random.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/random.py | Apache-2.0 |
def fork(self, name=_MODEL_PARALLEL_RNG_TRACKER_NAME):
"""Fork the cuda rng state, perform operations, and exit with the
original state."""
# Check if we have added the state
if name not in self.states_:
raise Exception("cuda rng state {} is not added".format(name))
#... | Fork the cuda rng state, perform operations, and exit with the
original state. | fork | python | inclusionAI/AReaL | realhf/impl/model/utils/random.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/random.py | Apache-2.0 |
def model_parallel_cuda_manual_seed(seed):
"""Initialize model parallel cuda seed.
This function should be called after the model parallel is
initialized. Also, no torch.cuda.manual_seed should be called
after this function. Basically, this is replacement for that
function.
Two set of RNG state... | Initialize model parallel cuda seed.
This function should be called after the model parallel is
initialized. Also, no torch.cuda.manual_seed should be called
after this function. Basically, this is replacement for that
function.
Two set of RNG states are tracked:
default state: This is for data... | model_parallel_cuda_manual_seed | python | inclusionAI/AReaL | realhf/impl/model/utils/random.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/random.py | Apache-2.0 |
def _initialize_affine_weight_gpu(
weight,
init_method,
partition_dim,
stride=1,
):
"""Initialize affine weight for model parallel on GPU."""
set_tensor_model_parallel_attributes(
tensor=weight, is_parallel=True, dim=partition_dim, stride=stride
)
init_method(weight) | Initialize affine weight for model parallel on GPU. | _initialize_affine_weight_gpu | python | inclusionAI/AReaL | realhf/impl/model/utils/random.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/random.py | Apache-2.0 |
def _initialize_affine_weight_cpu(
weight,
output_size,
input_size,
per_partition_size,
partition_dim,
init_method,
stride=1,
return_master_weight=False,
*,
params_dtype=torch.float32,
):
"""Initialize affine weight for model parallel.
Build the master weight on all proc... | Initialize affine weight for model parallel.
Build the master weight on all processes and scatter the relevant
chunk.
| _initialize_affine_weight_cpu | python | inclusionAI/AReaL | realhf/impl/model/utils/random.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/impl/model/utils/random.py | Apache-2.0 |
def monitor_log(
job_name: str, log_path: str, output_file: str, stop_event: threading.Event
):
"""Monitor a log file and write its contents to the output file with job name prefix."""
# Wait for log file to be created
while not os.path.exists(log_path) and not stop_event.is_set():
time.sleep(0.... | Monitor a log file and write its contents to the output file with job name prefix. | monitor_log | python | inclusionAI/AReaL | realhf/scheduler/slurm/client.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/scheduler/slurm/client.py | Apache-2.0 |
def __allocate_and_commit_pending_jobs(self):
"""Allocate resources to all pending job specs.
Generate hostfiles for each job info
"""
start_time = time.monotonic()
while True:
try:
fp = open(LOCK_FILE_NAME, "w")
fcntl.flock(fp, fcntl.... | Allocate resources to all pending job specs.
Generate hostfiles for each job info
| __allocate_and_commit_pending_jobs | python | inclusionAI/AReaL | realhf/scheduler/slurm/client.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/scheduler/slurm/client.py | Apache-2.0 |
def get_all_node_resources() -> Dict[str, SlurmResource]:
"""Execute `scontrol show node` to get all node resources available in the
slurm cluster.
Return a list of SlurmResource
"""
o = subprocess.check_output(["scontrol", "show", "node"]).decode("utf-8")
nodes = o.split("\n\n")
all_rres =... | Execute `scontrol show node` to get all node resources available in the
slurm cluster.
Return a list of SlurmResource
| get_all_node_resources | python | inclusionAI/AReaL | realhf/scheduler/slurm/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/scheduler/slurm/utils.py | Apache-2.0 |
def allocate_resources(
infos: List[SlurmLaunchInfo],
strategy: Literal["empty_first", "allocated_first"] = "empty_first",
) -> List[SlurmLaunchInfo]:
"""Allocate all slurm task specs, fill in the hostfile field of the specs.
All slurm tasks are scheduled in pack. There are two choices of allocating
... | Allocate all slurm task specs, fill in the hostfile field of the specs.
All slurm tasks are scheduled in pack. There are two choices of allocating
strategies. The first is `empty_first`, which means we first allocate
tasks to nodes with more free resources. The second is `allocated_first`,
which alloca... | allocate_resources | python | inclusionAI/AReaL | realhf/scheduler/slurm/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/scheduler/slurm/utils.py | Apache-2.0 |
def execute_shell_command(command: str) -> subprocess.Popen:
"""
Execute a shell command and return its process handle.
"""
# Replace newline continuations and split the command string.
command = command.replace("\\\n", " ").replace("\\", " ")
parts = command.split()
return subprocess.Popen(... |
Execute a shell command and return its process handle.
| execute_shell_command | python | inclusionAI/AReaL | realhf/system/generation_server.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/generation_server.py | Apache-2.0 |
def launch_server_cmd(command: str, port: int = 30000):
"""
Launch the server using the given command.
If no port is specified, a free port is reserved.
"""
if not ray.is_initialized():
apply_sglang_path()
assert port is not None
full_command = f"{command} --port {port}"
process ... |
Launch the server using the given command.
If no port is specified, a free port is reserved.
| launch_server_cmd | python | inclusionAI/AReaL | realhf/system/generation_server.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/generation_server.py | Apache-2.0 |
def wait_for_server(base_url: str, timeout: int = None) -> None:
"""Wait for the server to be ready by polling the /v1/models endpoint.
Args:
base_url: The base URL of the server
timeout: Maximum time to wait in seconds. None means wait forever.
"""
start_time = time.time()
while Tr... | Wait for the server to be ready by polling the /v1/models endpoint.
Args:
base_url: The base URL of the server
timeout: Maximum time to wait in seconds. None means wait forever.
| wait_for_server | python | inclusionAI/AReaL | realhf/system/generation_server.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/generation_server.py | Apache-2.0 |
def _run_routing_service(self):
"""Expose an API for clients to find the destination server."""
import uvicorn
from fastapi import FastAPI
self.app = FastAPI()
@self.app.post("/schedule_request")
async def schedule_request(req_meta: GenReqMeta):
with self.th... | Expose an API for clients to find the destination server. | _run_routing_service | python | inclusionAI/AReaL | realhf/system/gserver_manager.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/gserver_manager.py | Apache-2.0 |
async def _issue_generation(
self,
url: str,
qid: Hashable,
group_idx: int,
prompt_ids: List[int],
input_ids: List[int],
prev_logprobs: List[float],
version_start: int,
raw_gconfig: GenerationHyperparameters,
cur_server_version: int,
):... | Issue a generation request.
`input_ids` can be a partial prefix and longer than `prompt_ids`.
If model weights are updated, the KV cache will be refreshed,
otherwise the server will reuse the radix cache with no additional overhead.
| _issue_generation | python | inclusionAI/AReaL | realhf/system/partial_rollout.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/partial_rollout.py | Apache-2.0 |
def push(self, data: JSONType) -> None:
"""
Push JSON-compatible data efficiently.
Args:
data: JSON-serializable Python object
Raises:
TypeError: If data is not JSON-serializable
zmq.ZMQError: If ZeroMQ operation fails
"""
# Directly ... |
Push JSON-compatible data efficiently.
Args:
data: JSON-serializable Python object
Raises:
TypeError: If data is not JSON-serializable
zmq.ZMQError: If ZeroMQ operation fails
| push | python | inclusionAI/AReaL | realhf/system/push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/push_pull_stream.py | Apache-2.0 |
def pull(self, timeout_ms: Optional[int] = None):
"""
Pull and decode JSON data with configurable timeout.
Args:
timeout_ms: Optional timeout in seconds. If None, uses default_timeout_ms.
Returns:
Deserialized JSON-compatible Python object
Raises:
... |
Pull and decode JSON data with configurable timeout.
Args:
timeout_ms: Optional timeout in seconds. If None, uses default_timeout_ms.
Returns:
Deserialized JSON-compatible Python object
Raises:
queue.Empty: If no message available within timeout
... | pull | python | inclusionAI/AReaL | realhf/system/push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/push_pull_stream.py | Apache-2.0 |
def create_exact_match_pattern(string_list: List[Union[uuid.UUID, str]]) -> re.Pattern:
"""Create exact match patterns for filtering out the desired respones.
The pattern is used to filter request IDs.
"""
escaped_strings = [re.escape(str(s)) for s in string_list]
pattern = f"({'|'.join(escaped_str... | Create exact match patterns for filtering out the desired respones.
The pattern is used to filter request IDs.
| create_exact_match_pattern | python | inclusionAI/AReaL | realhf/system/request_reply_stream.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/request_reply_stream.py | Apache-2.0 |
def request(
self,
handlers: List[str | int] | None = None,
handle_type: str | None = None,
datas: List[Any] | None = None,
payloads: List[Payload] | None = None,
verbose: bool = True,
no_syn: bool = True,
) -> List[uuid.UUID]:
"""Send requests of type... | Send requests of type `handle_type` to all `handlers` with
corresponding `data`.
If no_syn is True, only send the requests without
synchronization.
Otherwise, wait for handlers' SYN message and respond with an
ACK. This protocol ensures that all handlers will receive the
... | request | python | inclusionAI/AReaL | realhf/system/request_reply_stream.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/request_reply_stream.py | Apache-2.0 |
def poll_batch(
self, pattern: re.Pattern | None = None, block: bool = False
) -> List[Payload]:
"""Collect responses that match some pattern from the stream.
This function may NOT actually pull from the stream. It may fetch something
from the buffer, which records mismatched respon... | Collect responses that match some pattern from the stream.
This function may NOT actually pull from the stream. It may fetch something
from the buffer, which records mismatched responses.
Args:
pattern (Optional[re.Pattern], optional): Only responses with this
speci... | poll_batch | python | inclusionAI/AReaL | realhf/system/request_reply_stream.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/request_reply_stream.py | Apache-2.0 |
def _pull_data_worker(self):
"""Worker thread that creates its own ZMQ puller and streams data."""
# Initialize the puller inside the worker thread
stream = NameResolvingZmqPuller(
constants.experiment_name(),
constants.trial_name(),
puller_index=self.util.dp_... | Worker thread that creates its own ZMQ puller and streams data. | _pull_data_worker | python | inclusionAI/AReaL | realhf/system/stream_dataset.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/stream_dataset.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.