Accelerate documentation

Thực hiện tích lũy gradient với Accelerate

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Thực hiện tích lũy gradient với Accelerate

Gradient accumulation là một kỹ thuật cho phép bạn huấn luyện với kích thước batch lớn hơn so với mức mà máy của bạn thường có thể chứa trong bộ nhớ. Kỹ thuật này được thực hiện bằng cách tích lũy gradient qua nhiều batch, và chỉ thực hiện bước cập nhật optimizer sau khi đã xử lý một số lượng batch nhất định.

Mặc dù về mặt kỹ thuật, mã tích lũy gradient chuẩn sẽ hoạt động tốt trong cấu hình phân tán, nhưng đây không phải là phương pháp hiệu quả nhất để thực hiện điều này và bạn có thể gặp phải tình trạng chậm đáng kể!

Trong hướng dẫn này, bạn sẽ thấy cách thiết lập nhanh chóng gradient accumulation và thực hiện nó bằng các tiện ích có sẵn trong Accelerate, chỉ cần thêm đúng một dòng code mới!

Ví dụ này sẽ sử dụng một vòng lặp huấn luyện PyTorch rất đơn giản, thực hiện tích lũy gradient mỗi hai lô:

device = "cuda"
model.to(device)

gradient_accumulation_steps = 2

for index, batch in enumerate(training_dataloader):
    inputs, targets = batch
    inputs = inputs.to(device)
    targets = targets.to(device)
    outputs = model(inputs)
    loss = loss_function(outputs, targets)
    loss = loss / gradient_accumulation_steps
    loss.backward()
    if (index + 1) % gradient_accumulation_steps == 0:
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()

Chuyển đổi sang Accelerate

Trước tiên, đoạn mã được hiển thị ở trên sẽ được chuyển đổi để sử dụng Accelerate mà không cần trình trợ giúp tích lũy gradient đặc biệt:

+ from accelerate import Accelerator
+ accelerator = Accelerator()

+ model, optimizer, training_dataloader, scheduler = accelerator.prepare(
+     model, optimizer, training_dataloader, scheduler
+ )

  for index, batch in enumerate(training_dataloader):
      inputs, targets = batch
-     inputs = inputs.to(device)
-     targets = targets.to(device)
      outputs = model(inputs)
      loss = loss_function(outputs, targets)
      loss = loss / gradient_accumulation_steps
+     accelerator.backward(loss)
      if (index+1) % gradient_accumulation_steps == 0:
          optimizer.step()
          scheduler.step()
          optimizer.zero_grad()

Ở trạng thái hiện tại, đoạn mã này sẽ không thực hiện tích lũy gradient một cách hiệu quả do một quá trình gọi là đồng bộ hóa gradient. Đọc thêm về điều đó trong tutorial về Khái niệm!

Để Accelerate xử lý tích lũy gradient

Những gì còn lại bây giờ là để Accelerate xử lý việc tích lũy gradient cho chúng ta. Để làm điều này, bạn nên truyền tham số gradient_accumulation_steps vào Accelerator, chỉ định số bước cần thực hiện trước mỗi lần gọi step() và cách tự động điều chỉnh loss trong lần gọi backward():

  from accelerate import Accelerator
- accelerator = Accelerator()
+ accelerator = Accelerator(gradient_accumulation_steps=2)

Ngoài ra, bạn có thể truyền tham số gradient_accumulation_plugin vào __init__ của đối tượng Accelerator, cho phép bạn tùy chỉnh thêm hành vi tích lũy gradient. Đọc thêm về điều đó trong tài liệu GradientAccumulationPlugin.

Từ đây, bạn có thể sử dụng trình quản lý ngữ cảnh accumulate() từ bên trong vòng lặp huấn luyện của mình để tự động thực hiện tích lũy gradient cho bạn! Bạn chỉ cần bọc nó quanh toàn bộ phần huấn luyện trong mã của chúng ta:

- for index, batch in enumerate(training_dataloader):
+ for batch in training_dataloader:
+     with accelerator.accumulate(model):
          inputs, targets = batch
          outputs = model(inputs)

Bạn có thể xóa tất cả các kiểm tra đặc biệt cho số bước và điều chỉnh loss:

- loss = loss / gradient_accumulation_steps
  accelerator.backward(loss)
- if (index+1) % gradient_accumulation_steps == 0:
  optimizer.step()
  scheduler.step()
  optimizer.zero_grad()

Như bạn có thể thấy, Accelerator có khả năng theo dõi số thứ tự của batch hiện tại và tự động xác định xem có nên thực hiện bước cập nhật cho optimizer đã được chuẩn bị hay không cũng như cách điều chỉnh loss.

Thông thường, khi sử dụng gradient accumulation, bạn cần điều chỉnh số bước để phản ánh sự thay đổi về tổng số batch mà bạn đang huấn luyện. Accelerate tự động thực hiện điều này cho bạn theo mặc định. Phía sau, chúng tôi khởi tạo một GradientAccumulationPlugin được cấu hình để thực hiện việc này.

state.GradientState được đồng bộ với dataloader đang được lặp qua. Do đó, nó giả định một cách đơn giản rằng khi đã đến cuối dataloader, mọi thứ sẽ được đồng bộ và một bước sẽ được thực hiện. Để tắt điều này, đặt sync_with_dataloader thành False trong GradientAccumulationPlugin:

from accelerate import Accelerator
from accelerate.utils import GradientAccumulationPlugin

plugin = GradientAccumulationPlugin(sync_with_dataloader=False)
accelerator = Accelerator(..., gradient_accumulation_plugin=plugin)

Mã hoàn chỉnh

Dưới đây là cài đặt hoàn chỉnh để thực hiện tích lũy gradient với Accelerate

from accelerate import Accelerator
accelerator = Accelerator(gradient_accumulation_steps=2)
model, optimizer, training_dataloader, scheduler = accelerator.prepare(
    model, optimizer, training_dataloader, scheduler
)
for batch in training_dataloader:
    with accelerator.accumulate(model):
        inputs, targets = batch
        outputs = model(inputs)
        loss = loss_function(outputs, targets)
        accelerator.backward(loss)
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()

Điều quan trọng là chỉ thực hiện một lần forward/backward bên trong context manager with accelerator.accumulate(model).

Để tìm hiểu thêm về những gì mà tính năng này bao bọc, hãy đọc hướng dẫn về khái niệm Đồng bộ hóa Gradient

Ví dụ tự chứa

Dưới đây là một ví dụ tự chứa mà bạn có thể chạy để xem cách tích lũy gradient hoạt động với Accelerate:

import torch
import copy
from accelerate import Accelerator
from accelerate.utils import set_seed
from torch.utils.data import TensorDataset, DataLoader

# seed
set_seed(0)

# define toy inputs and labels
x = torch.tensor([1., 2., 3., 4., 5., 6., 7., 8.])
y = torch.tensor([2., 4., 6., 8., 10., 12., 14., 16.])
gradient_accumulation_steps = 4
per_device_batch_size = len(x) // gradient_accumulation_steps

# define dataset and dataloader
dataset = TensorDataset(x, y)
dataloader = DataLoader(dataset, batch_size=per_device_batch_size)

# define model, optimizer and loss function
class SimpleLinearModel(torch.nn.Module):
    def __init__(self):
        super(SimpleLinearModel, self).__init__()
        self.weight = torch.nn.Parameter(torch.zeros((1, 1)))

    def forward(self, inputs):
        return inputs @ self.weight

model = SimpleLinearModel()
model_clone = copy.deepcopy(model)
criterion = torch.nn.MSELoss()
model_optimizer = torch.optim.SGD(model.parameters(), lr=0.02)
accelerator = Accelerator(gradient_accumulation_steps=gradient_accumulation_steps)
model, model_optimizer, dataloader = accelerator.prepare(model, model_optimizer, dataloader)
model_clone_optimizer = torch.optim.SGD(model_clone.parameters(), lr=0.02)
print(f"initial model weight is {model.weight.mean().item():.5f}")
print(f"initial model weight is {model_clone.weight.mean().item():.5f}")
for i, (inputs, labels) in enumerate(dataloader):
    with accelerator.accumulate(model):
        inputs = inputs.view(-1, 1)
        print(i, inputs.flatten())
        labels = labels.view(-1, 1)
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        accelerator.backward(loss)
        model_optimizer.step()
        model_optimizer.zero_grad()
loss = criterion(x.view(-1, 1) @ model_clone.weight, y.view(-1, 1))
model_clone_optimizer.zero_grad()
loss.backward()
model_clone_optimizer.step()
print(f"w/ accumulation, the final model weight is {model.weight.mean().item():.5f}")
print(f"w/o accumulation, the final model weight is {model_clone.weight.mean().item():.5f}")
initial model weight is 0.00000
initial model weight is 0.00000
0 tensor([1., 2.])
1 tensor([3., 4.])
2 tensor([5., 6.])
3 tensor([7., 8.])
w/ accumulation, the final model weight is 2.04000
w/o accumulation, the final model weight is 2.04000

Tích lũy gradient trên các mẫu huấn luyện có kích thước khác nhau

Như đã được chỉ ra trong bài đăng trên blog này, trong đó nêu rõ một lỗi thường gặp khi thực hiện tích lũy gradient trên các mẫu huấn luyện có kích thước khác nhau:

[…] đối với tích lũy gradient trên các tác vụ ở cấp độ token như huấn luyện LM nhân quả, loss đúng nên được tính bằng tổng loss trên tất cả các batch trong một bước tích lũy gradient chia cho tổng số token không phải padding trong các batch đó. Điều này không giống với giá trị trung bình của các loss trên từng batch.

Nói cách khác, một số điều chỉnh phải được thực hiện đối với các hàm mất (losses) hoạt động ở cấp độ token.

Đếm số mục tiêu thực sự đóng góp vào loss. Đối với các mô hình ngôn ngữ causal của Transformers tự dịch chuyển nhãn bên trong, truyền nhãn chưa được dịch chuyển và đếm (labels[..., 1:] != -100).sum(): nhãn đầu tiên không có dự đoán đi trước. Không dịch chuyển lại các nhãn đó trong data collator. Ví dụ tích lũy tự hồi quy sử dụng quy ước này; các hàm loss khác có thể sử dụng cách căn chỉnh mục tiêu khác.

Mã khung

from accelerate import Accelerator
import math
import contextlib

gradient_accumulation_steps = 2
accelerator = Accelerator(gradient_accumulation_steps=gradient_accumulation_steps)
model, optimizer, training_dataloader, scheduler = accelerator.prepare(
    model, optimizer, training_dataloader, scheduler
)

training_iterator = iter(training_dataloader)
num_samples_in_epoch = len(training_dataloader)
remainder = num_samples_in_epoch % gradient_accumulation_steps
remainder = remainder if remainder != 0 else gradient_accumulation_steps
total_updates = math.ceil(num_samples_in_epoch / gradient_accumulation_steps)
        

total_batched_samples = 0
for update_step in range(total_updates):
        # In order to correctly the total number of non-padded tokens on which we'll compute the cross-entropy loss
        # we need to pre-load the full local batch - i.e the next per_device_batch_size * accumulation_steps samples
        batch_samples = []
        num_batches_in_step = gradient_accumulation_steps if update_step != (total_updates - 1) else remainder
        for _ in range(num_batches_in_step):
            batch_samples += [next(training_iterator)]
            
        # get local num items in batch 
        num_items_in_batch = sum([(batch["labels"].ne(-100)).sum() for batch in batch_samples])
        # to compute it correctly in a multi-device DDP training, we need to gather the total number of items in the full batch.
        num_items_in_batch = accelerator.gather(num_items_in_batch).sum().item()
            
        for i, batch in enumerate(batch_samples):
            # if we perform gradient accumulation in a multi-devices set-up, we want to avoid unnecessary communications when accumulating
            # cf: https://muellerzr.github.io/blog/gradient_accumulation.html
            if (i < len(batch_samples) - 1 and accelerator.num_processes > 1):
                ctx = model.no_sync
            else:
                ctx = contextlib.nullcontext
            
            total_batched_samples += 1

            with ctx():
                inputs, targets = batch
                outputs = model(inputs)
                loss = loss_function(outputs, targets) # the loss function should sum over samples rather than averaging
                
                # We multiply by num_processes because the DDP calculates the average gradient across all devices whereas dividing by num_items_in_batch already takes into account all devices
                # Same reason for gradient_accumulation_steps, but this times it's Accelerate that calculate the average gradient across the accumulated steps
                loss = (loss * gradient_accumulation_steps * accelerator.num_processes) / num_items_in_batch
                
                accelerator.backward(loss)

        # Sync gradients and perform optimization steps once every gradient_accumulation_steps
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()

Ví dụ LM nhân quả tự chứa

import torch
import copy
from accelerate import Accelerator
from accelerate.utils import set_seed
from accelerate.logging import  get_logger
from torch.utils.data import Dataset, DataLoader
import math
import contexlib

# seed
set_seed(0)
logger = get_logger(__name__)

class MyDataset(Dataset):
    def __init__(self, num_samples):
        super().__init__()
        self.len = num_samples

    def __getitem__(self, index):
        input_ids = torch.arange(1, index+2, dtype=torch.float32)
        labels = torch.remainder(input_ids, 2)
        return {"input_ids": input_ids, "labels": labels}

    def __len__(self):
        return self.len
    
def collate_fn(features):
    input_ids = torch.nn.utils.rnn.pad_sequence([f["input_ids"] for f in features], batch_first=True, padding_value=-100)
    labels = torch.nn.utils.rnn.pad_sequence([f["labels"] for f in features], batch_first=True, padding_value=-100)
    return {"input_ids": input_ids[..., None], "labels": labels[..., None]}

# define toy inputs and labels
gradient_accumulation_steps = 2
per_device_batch_size = 4

# define accelerator
accelerator = Accelerator(gradient_accumulation_steps=gradient_accumulation_steps)

# define dataset and dataloader
# for this toy example, we'll compute gradient descent over one single global batch
dataset = MyDataset(per_device_batch_size*gradient_accumulation_steps*accelerator.num_processes)
dataloader = DataLoader(dataset, batch_size=per_device_batch_size, collate_fn=collate_fn)

# define model, model_optimizer and loss function
model = torch.nn.Linear(1, 2, bias=False)
model_clone = copy.deepcopy(model)
criterion = torch.nn.CrossEntropyLoss(reduction="sum") # must sum over samples rather than averaging
model_optimizer = torch.optim.SGD(model.parameters(), lr=0.08)


logger.warning(f"initial model weight is {model.weight.detach().cpu().squeeze()}")
logger.warning(f"initial model clone weight is {model_clone.weight.detach().cpu().squeeze()}")

# prepare artifacts - accelerator handles device placement and dataloader splitting
model, model_optimizer = accelerator.prepare(model, model_optimizer)
dataloader = accelerator.prepare_data_loader(dataloader, device_placement=True)
training_iterator = iter(dataloader)

num_samples_in_epoch = len(dataloader)
remainder = num_samples_in_epoch % gradient_accumulation_steps
remainder = remainder if remainder != 0 else gradient_accumulation_steps
total_gradient_updates = math.ceil(num_samples_in_epoch / gradient_accumulation_steps)

total_batched_samples = 0
for update_step in range(total_gradient_updates):
        # In order to correctly the total number of non-padded tokens on which we'll compute the cross-entropy loss
        # we need to pre-load the full local batch - i.e the next per_device_batch_size * accumulation_steps samples
        batch_samples = []
        num_batches_in_step = gradient_accumulation_steps if update_step != (total_gradient_updates - 1) else remainder
        for _ in range(num_batches_in_step):
            batch_samples += [next(training_iterator)]
            
        # get local num items in batch 
        local_num_items_in_batch = sum([(batch["labels"].ne(-100)).sum() for batch in batch_samples])
        logger.warning(f"Step {update_step} - Device {accelerator.process_index} - num items in the local batch {local_num_items_in_batch}", main_process_only=False)

        # to compute it correctly in a multi-device DDP training, we need to gather the total number of items in the full batch.
        num_items_in_batch = accelerator.gather(local_num_items_in_batch).sum().item()
        logger.warning(f"Total num items {num_items_in_batch}")

        for i, batch in enumerate(batch_samples):
            inputs, labels = batch["input_ids"], batch["labels"]
            total_batched_samples += 1
            # if we perform gradient accumulation in a multi-devices set-up, we want to avoid unnecessary communications when accumulating
            # cf: https://muellerzr.github.io/blog/gradient_accumulation.html
            if (i < len(batch_samples) - 1 and accelerator.num_processes > 1):
                ctx = model.no_sync
            else:
                ctx = contextlib.nullcontext
            with ctx():

                outputs = model(inputs)
                loss = criterion(outputs.view(-1, 2), labels.view(-1).to(torch.int64))
                
                # We multiply by num_processes because the DDP calculates the average gradient across all devices whereas dividing by num_items_in_batch already takes into account all devices
                # Same reason for gradient_accumulation_steps, but this times it's Accelerate that calculate the average gradient across the accumulated steps 
                loss = (loss * gradient_accumulation_steps * accelerator.num_processes) / num_items_in_batch
                accelerator.backward(loss)
        model_optimizer.step()
        model_optimizer.zero_grad()
                

logger.warning(f"Device {accelerator.process_index} - w/ accumulation, the final model weight is {accelerator.unwrap_model(model).weight.detach().cpu().squeeze()}", main_process_only=False)

# We know do the same operation but on a single device and without gradient accumulation

if accelerator.is_main_process:
    # prepare one single entire batch
    dataloader = DataLoader(dataset, batch_size=len(dataset), collate_fn=collate_fn)
    full_batch_without_accum = next(iter(dataloader))
    total_inputs, total_labels = full_batch_without_accum["input_ids"], full_batch_without_accum["labels"]
    model_clone_optimizer = torch.optim.SGD(model_clone.parameters(), lr=0.08)
    
    # train the cloned model
    loss = torch.nn.CrossEntropyLoss(reduction="mean")(model_clone(total_inputs).view(-1, 2), total_labels.view(-1).to(torch.int64))
    model_clone_optimizer.zero_grad()
    loss.backward()
    model_clone_optimizer.step()
    
    # We should have the same final weights.
    logger.warning(f"w/o accumulation, the final model weight is {model_clone.weight.detach().cpu().squeeze()}")

Kết quả trên một thiết bị duy nhất - số bước tích lũy gradient được đặt là 1 và batch_size được đặt là 8:

initial model weight is tensor([-0.0075,  0.5364])
initial model clone weight is tensor([-0.0075,  0.5364])
Step 0 - Device 0 - num items in the local batch 36
Total num items 36
Device 0 - w/ accumulation, the final model weight is tensor([0.0953, 0.4337])
w/o accumulation, the final model weight is tensor([0.0953, 0.4337])

Kết quả trên cấu hình hai thiết bị - số bước tích lũy gradient được đặt là 2 và batch_size được đặt là 4.

initial model weight is tensor([-0.0075,  0.5364])
initial model clone weight is tensor([-0.0075,  0.5364])
Step 0 - Device 0 - num items in the local batch 52
Step 0 - Device 1 - num items in the local batch 84
Total num items 136
Device 1 - w/ accumulation, the final model weight is tensor([0.2117, 0.3172])
Device 0 - w/ accumulation, the final model weight is tensor([0.2117, 0.3172])
w/o accumulation, the final model weight is tensor([0.2117, 0.3172])

Để đi xa hơn:

Hãy xem một kịch bản ví dụ hoàn chỉnh về một lượt huấn luyện thực tế trong thư mục examples tại đường dẫn accelerate/examples/by_feature/gradient_accumulation_for_autoregressive_models.py.

Chạy trên một số cấu hình huấn luyện với kích thước lô toàn cục không đổi bằng 32 cho ra đồ thị sau:

Lưu ý rằng các tổn thất huấn luyện hoàn toàn giống nhau cho đến bước huấn luyện 20. Sự sai lệch nhỏ sau bước huấn luyện này xảy ra ngay ở cuối epoch đầu tiên, vì, theo mặc định, dataloader sẽ nhân bản các mẫu ở đầu bộ dữ liệu khi tổng kích thước lô không chia hết chính xác cho bộ dữ liệu.

Update on GitHub