# Megatron-LM 유틸리티

## MegatronLMPlugin[[accelerate.utils.MegatronLMPlugin]]

#### accelerate.utils.MegatronLMPlugin[[accelerate.utils.MegatronLMPlugin]]

```python
accelerate.utils.MegatronLMPlugin(tp_degree: int = None, pp_degree: int = None, use_custom_fsdp: bool = None, overlap_cpu_optimizer_d2h_h2d: bool = None, no_load_optim: bool = None, eod_mask_loss: bool = None, no_save_optim: bool = None, optimizer_cpu_offload: bool = None, use_precision_aware_optimizer: bool = None, decoder_last_pipeline_num_layers: int = None, recompute_granularity: str = None, recompute_method: str = None, recompute_num_layers: int = None, attention_backend: bool = None, expert_model_parallel_size: int = None, context_parallel_size: int = None, attention_dropout: float = None, hidden_dropout: float = None, attention_softmax_in_fp32: bool = None, expert_tensor_parallel_size: int = None, calculate_per_token_loss: bool = None, use_rotary_position_embeddings: bool = None, num_micro_batches: int = None, gradient_clipping: float = None, sequence_parallelism: bool = None, recompute_activations: bool = None, use_distributed_optimizer: bool = None, pipeline_model_parallel_split_rank: int = None, num_layers_per_virtual_pipeline_stage: int = None, is_train_batch_min: str = True, train_iters: int = None, train_samples: int = None, weight_decay_incr_style: str = 'constant', start_weight_decay: float = None, end_weight_decay: float = None, lr_decay_style: str = 'linear', lr_decay_iters: int = None, lr_decay_samples: int = None, lr_warmup_iters: int = None, lr_warmup_samples: int = None, lr_warmup_fraction: float = None, min_lr: float = 0, consumed_samples: list[int] = None, no_wd_decay_cond: typing.Callable | None = None, scale_lr_cond: typing.Callable | None = None, lr_mult: float = 1.0, megatron_dataset_flag: bool = False, seq_length: int = None, encoder_seq_length: int = None, decoder_seq_length: int = None, tensorboard_dir: str = None, set_all_logging_options: bool = False, eval_iters: int = 100, eval_interval: int = 1000, return_logits: bool = False, custom_train_step_class: typing.Any | None = None, custom_train_step_kwargs: dict[str, typing.Any] | None = None, custom_model_provider_function: typing.Callable | None = None, custom_prepare_model_function: typing.Callable | None = None, custom_megatron_datasets_provider_function: typing.Callable | None = None, custom_get_batch_function: typing.Callable | None = None, custom_loss_function: typing.Callable | None = None, other_megatron_args: dict[str, typing.Any] | None = None)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/dataclasses.py#L2211)

**매개변수:**

tp_degree (`int`, 기본값 `None`) : Tensor parallelism degree.

pp_degree (`int`, 기본값 `None`) : 파이프라인 병렬도입니다.

num_micro_batches (`int`, 기본값 `None`) : 마이크로 배치의 수.

gradient_clipping (`float`, 기본값 `None`) : 전역 L2 노름 기반의 그라디언트 클리핑 값(0이면 비활성화).

sequence_parallelism (`bool`, 기본값 `None`) : 시퀀스 병렬화를 활성화합니다.

recompute_activations (`bool`, 기본값 `None`) : 선택적 활성화 재계산을 활성화합니다.

use_distributed_optimizer (`bool`, 기본값 `None`) : 분산 옵티마이저를 활성화합니다.

pipeline_model_parallel_split_rank (`int`, 기본값 `None`) : 인코더와 디코더를 분리할 랭크.

num_layers_per_virtual_pipeline_stage (`int`, 기본값 `None`) : 가상 파이프라인 단계당 레이어 수.

is_train_batch_min (`str`, 기본값 `True`) : tran 및 eval dataloader가 모두 지정된 경우, `micro_batch_size`를 결정합니다.

train_iters (`int`, 기본값 `None`) : 모든 학습 실행에 걸쳐 학습할 샘플의 총 개수. `MegatronLMDummyScheduler`를 사용할 때는 train-iters 또는 train-samples 중 하나를 제공해야 합니다.

train_samples (`int`, 기본값 `None`) : 모든 학습 실행에 걸쳐 학습할 샘플의 총 개수. `MegatronLMDummyScheduler`를 사용할 때는 train-iters 또는 train-samples 중 하나를 제공해야 합니다.

weight_decay_incr_style (`str`, 기본값 `'constant'`) : 가중치 감쇠 증분 함수. choices=["constant", "linear", "cosine"].

start_weight_decay (`float`, 기본값 `None`) : L2 정규화를 위한 초기 weight decay 계수입니다.

end_weight_decay (`float`, 기본값 `None`) : L2 정규화를 위한 실행 종료 시 weight decay 계수.

lr_decay_style (`str`, 기본값 `'linear'`) : 학습률 감쇠 함수. choices=['constant', 'linear', 'cosine'].

lr_decay_iters (`int`, 기본값 `None`) : 학습률 감쇠를 위한 반복 횟수입니다. None인 경우 기본값은 `train_iters`입니다.

lr_decay_samples (`int`, 기본값 `None`) : 학습률 감쇠를 위한 샘플 수. None인 경우 기본값은 `train_samples`입니다.

lr_warmup_iters (`int`, 기본값 `None`) : 학습률을 선형으로 워밍업할 반복 횟수.

lr_warmup_samples (`int`, 기본값 `None`) : 학습률을 선형으로 워밍업할 샘플 수.

lr_warmup_fraction (`float`, 기본값 `None`) : 학습률을 선형으로 워밍업할 lr-warmup-(iters/samples)의 비율.

min_lr (`float`, 기본값 `0`) : 학습률의 최소값입니다. 스케줄러는 이 임계값보다 작은 값을 잘라냅니다.

consumed_samples (`List`, 기본값은 `None`) : `accelerator.prepare` 호출에 사용된 dataloader와 동일한 순서로 소비된 샘플 수.

no_wd_decay_cond (`Optional`, 기본값은 `None`) : weight decay를 비활성화할 조건.

scale_lr_cond (`Optional`, 기본값은 `None`) : 학습률을 스케일링할 조건.

lr_mult (`float`, 기본값 `1.0`) : 학습률 배율.

megatron_dataset_flag (`bool`, 기본값 `False`) : 데이터셋의 형식이 Megatron-LM Indexed/Cached/MemoryMapped 형식을 따르는지 여부.

seq_length (`int`, 기본값 `None`) : 처리할 최대 시퀀스 길이입니다.

encoder_seq_length (`int`, 기본값 `None`) : 인코더에서 처리할 최대 시퀀스 길이입니다.

decoder_seq_length (`int`, 기본값 `None`) : 디코더에서 처리할 최대 시퀀스 길이입니다.

tensorboard_dir (`str`, 기본값 `None`) : tensorboard 로그를 저장할 경로.

set_all_logging_options (`bool`, 기본값 `False`) : 모든 로깅 옵션을 설정할지 여부.

eval_iters (`int`, 기본값 `100`) : 평가용 validation/test를 실행할 반복 횟수.

eval_interval (`int`, 기본값 `1000`) : 검증 세트에서 평가를 실행하는 간격.

return_logits (`bool`, 기본값 `False`) : 모델에서 logits를 반환할지 여부.

custom_train_step_class (`Optional`, 기본값은 `None`) : 사용자 정의 학습 단계 클래스.

custom_train_step_kwargs (`Optional`, 기본값은 `None`) : 사용자 정의 train step kwargs.

custom_model_provider_function (`Optional`, 기본값은 `None`) : 사용자 지정 모델 제공자 함수.

custom_prepare_model_function (`Optional`, 기본값은 `None`) : 사용자 정의 prepare model 함수.

custom_megatron_datasets_provider_function (`Optional`, 기본값은 `None`) : 사용자 정의 megatron train_valid_test 데이터셋 제공자 함수.

custom_get_batch_function (`Optional`, 기본값은 `None`) : 사용자 정의 get batch 함수.

custom_loss_function (`Optional`, 기본값은 `None`) : 사용자 정의 손실 함수.

other_megatron_args (`Optional`, 기본값은 `None`) : 기타 Megatron-LM 인자. Megatron-LM을 참고하세요.

tensor, pipeline, sequence 및 data 병렬화를 활성화하는 Megatron-LM용 플러그인입니다. 또한 선택적 활성화 재계산과 최적화된 융합 커널을 활성화합니다.

## MegatronLMDummyScheduler[[accelerate.utils.MegatronLMDummyScheduler]]

#### accelerate.utils.MegatronLMDummyScheduler[[accelerate.utils.MegatronLMDummyScheduler]]

```python
accelerate.utils.MegatronLMDummyScheduler(optimizer, total_num_steps = None, warmup_num_steps = 0, **kwargs)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/megatron_lm.py#L378)

**매개변수:**

optimizer (`torch.optim.optimizer.Optimizer`) : 래핑할 옵티마이저.

total_num_steps (int) : 총 스텝 수.

warmup_num_steps (int) : 워밍업 단계 수.

- ****kwargs** (추가 키워드 인자, *선택*) : 기타 인자.

Dummy scheduler는 모델 파라미터 또는 파라미터 그룹을 제시하며, 이는 주로 deepspeed 설정 파일에 스케줄러 구성이 지정된 경우 전통적인 학습 루프를 따르기 위해 사용됩니다.

## MegatronLMDummyDataLoader[[accelerate.utils.MegatronLMDummyDataLoader]]

#### accelerate.utils.MegatronLMDummyDataLoader[[accelerate.utils.MegatronLMDummyDataLoader]]

```python
accelerate.utils.MegatronLMDummyDataLoader(**dataset_kwargs)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/megatron_lm.py#L162)

**매개변수:**

- ****dataset_kwargs** : Megatron 데이터 인자.

Dummy dataloader는 모델 파라미터 또는 파라미터 그룹을 제공하며, 이는 주로 일반적인 학습을 따르기 위해 사용됩니다.

## AbstractTrainStep[[accelerate.utils.AbstractTrainStep]]

#### accelerate.utils.AbstractTrainStep[[accelerate.utils.AbstractTrainStep]]

```python
accelerate.utils.AbstractTrainStep(name)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/megatron_lm.py#L415)

배치 처리, forward pass 및 손실 처리를 위한 추상 클래스.

## GPTTrainStep[[accelerate.utils.GPTTrainStep]]

#### accelerate.utils.GPTTrainStep[[accelerate.utils.GPTTrainStep]]

```python
accelerate.utils.GPTTrainStep(accelerator, args)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/megatron_lm.py#L574)

**매개변수:**

args (`argparse.Namespace`) : Megatron-LM 인자.

GPT 학습 단계 클래스.

## BertTrainStep[[accelerate.utils.BertTrainStep]]

#### accelerate.utils.BertTrainStep[[accelerate.utils.BertTrainStep]]

```python
accelerate.utils.BertTrainStep(accelerator, args)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/megatron_lm.py#L432)

**매개변수:**

args (`argparse.Namespace`) : Megatron-LM 인자.

Bert 학습 단계 클래스.

## T5TrainStep[[accelerate.utils.T5TrainStep]]

#### accelerate.utils.T5TrainStep[[accelerate.utils.T5TrainStep]]

```python
accelerate.utils.T5TrainStep(accelerator, args)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/megatron_lm.py#L718)

**매개변수:**

args (`argparse.Namespace`) : Megatron-LM 인자.

T5 학습 단계 클래스.

## avg_losses_across_data_parallel_group[[accelerate.utils.avg_losses_across_data_parallel_group]]

#### accelerate.utils.avg_losses_across_data_parallel_group[[accelerate.utils.avg_losses_across_data_parallel_group]]

```python
accelerate.utils.avg_losses_across_data_parallel_group(losses)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/megatron_lm.py#L1217)

**매개변수:**

losses (List[Tensor]) : 데이터 병렬 그룹에 걸쳐 평균을 내야 할 손실 목록.

데이터 병렬 그룹 전체의 평균 손실.

