BR的头像Blog
  • 首页
  • 关于
  • 博客
  • 日常
  • 相册
  • 音乐馆
  • 经历
  • 作品集
  • 归档
  • 学术档案

Powered by Next.js

© 2026 BR. All rights reserved.

cd ../blog
未分类

从零构建GPT-2(四)

BR2026-11-22预计阅读 36 分钟
从零构建GPT-24 篇展开/收起
01
从零构建GPT-2(一)
  • 02从零构建GPT-2(二)
  • 03从零构建GPT-2(三)
  • 04从零构建GPT-2(四)
  • 注意

    本系列搬运自旧站,发布于2024.12.3.

    从零构建GPT-2(四)

    数据集

    gpt-2的训练使用了从未发布的WebText数据集,但是有一个名为OpenWebText的数据集尝试复现它。在论文中,openai提到,他们从reddit上抓取了所有的出站连接,这应该是他们构建数据集的起点,他们收集了所有网页和其中的所有文本,一共4500万个链接和40GB的文本。在gpt-3的技术报告中提到训练数据集部分,他们讨论了目前更常用的Common Crawl,但这并不是一个高质量的数据集,因为他非常noisy,当然里面也有一些非常高质量的数据,因此过滤该数据集也成了一个比较重要的工作。除此之外,也可以使用别的互联网网页数据、书籍、Wikipedia等数据集进行训练,但gpt-3的训练数据集也从未发布过。在Karpathy的课程中,他推荐了一些他熟悉的相当不错并具有代表性的数据集:

    1. RedPajama以及它的子集SlimPajama,后者是前者清理重复数据后的版本
    2. FineWeb一个近期发布的数据集,收集了高质量Common Crawl数据并过滤后的成果。并且最近HuggingFace还发布了edu版本的FineWebEdu包含了1.3T的educational和5.4T的high-educational的内容

    在这里,我们使用FineWebEdu的sample-10BT(最小的一组子集)进行训练,这足以让我们这个大小的小模型训练至接近gpt-2的性能了。

    数据集下载

    这里给出数据集的下载和预处理脚本(以下代码完全来自Karpathy):

    python
    """
    FineWeb-Edu dataset (for srs pretraining)
    https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu
    Downloads and tokenizes the data and saves data shards to disk.
    Run simply as:
    $ python fineweb.py
    Will save shards to the local directory "edu_fineweb10B".
    """
    
    import os
    import multiprocessing as mp
    import numpy as np
    import tiktoken
    from datasets import load_dataset # pip install datasets
    from tqdm import tqdm # pip install tqdm
    
    # ------------------------------------------
    local_dir = "edu_fineweb10B"
    remote_name = "sample-10BT"
    shard_size = int(1e8) # 100M tokens per shard, total of 100 shards
    
    # create the cache the local directory if it doesn't exist yet
    DATA_CACHE_DIR = os.path.join(os.path.dirname(__file__), local_dir)
    os.makedirs(DATA_CACHE_DIR, exist_ok=True)
    
    # download the dataset
    fw = load_dataset("HuggingFaceFW/fineweb-edu", name=remote_name, split="train")
    
    # init the tokenizer
    enc = tiktoken.get_encoding("gpt2")
    eot = enc._special_tokens['<|endoftext|>'] # end of text token
    def tokenize(doc):
        # tokenizes a single document and returns a numpy array of uint16 tokens
        tokens = [eot] # the special <|endoftext|> token delimits all documents
        tokens.extend(enc.encode_ordinary(doc["text"]))
        tokens_np = np.array(tokens)
        assert (0 <= tokens_np).all() and (tokens_np < 2**16).all(), "token dictionary too large for uint16"
        tokens_np_uint16 = tokens_np.astype(np.uint16)
        return tokens_np_uint16
    
    def write_datafile(filename, tokens_np):
        np.save(filename, tokens_np)
    
    # tokenize all documents and write output shards, each of shard_size tokens (last shard has remainder)
    nprocs = max(1, os.cpu_count()//2)
    with mp.Pool(nprocs) as pool:
        shard_index = 0
        # preallocate buffer to hold current shard
        all_tokens_np = np.empty((shard_size,), dtype=np.uint16)
        token_count = 0
        progress_bar = None
        for tokens in pool.imap(tokenize, fw, chunksize=16):
    
            # is there enough space in the current shard for the new tokens?
            if token_count + len(tokens) < shard_size:
                # simply append tokens to current shard
                all_tokens_np[token_count:token_count+len(tokens)] = tokens
                token_count += len(tokens)
                # update progress bar
                if progress_bar is None:
                    progress_bar = tqdm(total=shard_size, unit="tokens", desc=f"Shard {shard_index}")
                progress_bar.update(len(tokens))
            else:
                # write the current shard and start a new one
                split = "val" if shard_index == 0 else "train"
                filename = os.path.join(DATA_CACHE_DIR, f"edufineweb_{split}_{shard_index:06d}")
                # split the document into whatever fits in this shard; the remainder goes to next one
                remainder = shard_size - token_count
                progress_bar.update(remainder)
                all_tokens_np[token_count:token_count+remainder] = tokens[:remainder]
                write_datafile(filename, all_tokens_np)
                shard_index += 1
                progress_bar = None
                # populate the next shard with the leftovers of the current doc
                all_tokens_np[0:len(tokens)-remainder] = tokens[remainder:]
                token_count = len(tokens)-remainder
    
        # write any remaining tokens as the last shard
        if token_count != 0:
            split = "val" if shard_index == 0 else "train"
            filename = os.path.join(DATA_CACHE_DIR, f"edufineweb_{split}_{shard_index:06d}")
            write_datafile(filename, all_tokens_np[:token_count])

    考虑到国内连接hf并不可靠,并且modelscope也收录了该数据集,经过测试,我自己重新整理了一套用于在modelscope上下载并保存数据集的脚本,并修复了其中我遇到的所有bug(经本人测试在windows和ubuntu上均运行并下载成功)。首先给出环境要求:

    bash
    pip install modelscope==1.20.1 datasets==2.16.0 oss2 addict

    这里之所以要指定modelscope和datasets的版本号是因为modelscope在数据集部分使用了datasets的backend,经过我的测试,这两个版本的组合可以成功运行代码并下载数据集,否则可能因为版本不匹配出现一些奇怪的bug比如:

    bash
    cannot import name 'OfflineModeIsEnabled' from 'datasets.utils.file_utils'

    然后给出我修改后的完整代码:

    python
    """
    FineWeb-Edu dataset (for srs pretraining)
    https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu
    Downloads and tokenizes the data and saves data shards to disk.
    Run simply as:
    $ python fineweb.py
    Will save shards to the local directory "edu_fineweb10B".
    """
    
    import os
    import multiprocessing as mp
    import numpy as np
    import tiktoken
    from modelscope.msdatasets import MsDataset
    from tqdm import tqdm # pip install tqdm
    
    
    # ------------------------------------------
    local_dir = "edu_fineweb10B"
    remote_name = "sample-10BT"
    shard_size = int(1e8) # 100M tokens per shard, total of 100 shards
    
    # create the cache the local directory if it doesn't exist yet
    DATA_CACHE_DIR = os.path.join(os.path.dirname(__file__), local_dir)
    os.makedirs(DATA_CACHE_DIR, exist_ok=True)
    
    # download the dataset
    fw = MsDataset.load('AI-ModelScope/fineweb-edu', subset_name=remote_name, cache_dir="./cache", split="train")
    
    # init the tokenizer
    enc = tiktoken.get_encoding("gpt2")
    eot = enc._special_tokens['<|endoftext|>'] # end of text token
    def tokenize(doc):
        # tokenizes a single document and returns a numpy array of uint16 tokens
        tokens = [eot] # the special <|endoftext|> token delimits all documents
        tokens.extend(enc.encode_ordinary(doc["text"]))
        tokens_np = np.array(tokens)
        assert (0 <= tokens_np).all() and (tokens_np < 2**16).all(), "token dictionary too large for uint16"
        tokens_np_uint16 = tokens_np.astype(np.uint16)
        return tokens_np_uint16
    
    def write_datafile(filename, tokens_np):
        np.save(filename, tokens_np)
    
    # tokenize all documents and write output shards, each of shard_size tokens (last shard has remainder)
    if __name__ == "__main__": # 这一行很重要,不然无法在windows上启动多线程
        nprocs = max(1, os.cpu_count()//2)
        with mp.Pool(nprocs) as pool:
            shard_index = 0
            # preallocate buffer to hold current shard
            all_tokens_np = np.empty((shard_size,), dtype=np.uint16)
            token_count = 0
            progress_bar = None
            for tokens in pool.imap(tokenize, fw, chunksize=16):
    
                # is there enough space in the current shard for the new tokens?
                if token_count + len(tokens) < shard_size:
                    # simply append tokens to current shard
                    all_tokens_np[token_count:token_count+len(tokens)] = tokens
                    token_count += len(tokens)
                    # update progress bar
                    if progress_bar is None:
                        progress_bar = tqdm(total=shard_size, unit="tokens", desc=f"Shard {shard_index}")
                    progress_bar.update(len(tokens))
                else:
                    # write the current shard and start a new one
                    split = "val" if shard_index == 0 else "train"
                    filename = os.path.join(DATA_CACHE_DIR, f"edufineweb_{split}_{shard_index:06d}")
                    # split the document into whatever fits in this shard; the remainder goes to next one
                    remainder = shard_size - token_count
                    progress_bar.update(remainder)
                    all_tokens_np[token_count:token_count+remainder] = tokens[:remainder]
                    write_datafile(filename, all_tokens_np)
                    shard_index += 1
                    progress_bar = None
                    # populate the next shard with the leftovers of the current doc
                    all_tokens_np[0:len(tokens)-remainder] = tokens[remainder:]
                    token_count = len(tokens)-remainder
    
            # write any remaining tokens as the last shard
            if token_count != 0:
                split = "val" if shard_index == 0 else "train"
                filename = os.path.join(DATA_CACHE_DIR, f"edufineweb_{split}_{shard_index:06d}")
                write_datafile(filename, all_tokens_np[:token_count])

    接下来是非常重要的一步,可能由于一些版本或者维护原因,这个代码存在一个很奇怪的bug,就是当数据集下载完成后,运行代码会出现一个无法从代码层面解决的问题(至少我到现在还没找到很好的办法),因此这里我提供的解决方案是修改modelscope的源码,找到路径:

    bash
    path to you env/site-packages/modelscope/msdatasets/utils/hf_datasets_util.py

    脚本,找到91行的_download_ms函数,将函数修改为:

    python
    def _download_ms(self, url_or_filename: str, download_config: DownloadConfig) -> str:
        url_or_filename = str(url_or_filename)
        # for temp val
        revision = None
        if url_or_filename.startswith('hf://'):
            revision, url_or_filename = url_or_filename.split('@', 1)[-1].split('/', 1)
        if url_or_filename.startswith("./cache"): # 这里的./cache需要和之前下载脚本里的cache_dir参数一致
            pass
        elif is_relative_path(url_or_filename):
            # append the relative path to the base_path
            # url_or_filename = url_or_path_join(self._base_path, url_or_filename)
            revision = revision or 'master'
            # Note: make sure the FilePath is the last param
            params: dict = {'Source': 'SDK', 'Revision': revision, 'FilePath': url_or_filename}
            params: str = urlencode(params)
            url_or_filename = self._base_path + params
    
        out = cached_path(url_or_filename, download_config=download_config)
        out = tracked_str(out)
        out.set_origin(url_or_filename)
        return out

    然后运行我给出的主脚本,就可以从modelscope上下载并预处理数据集了。需要注意的是subset sample-10B一共会整理出99条shard,处理数据的时候耐心等待即可。

    我在hf上还找到了一个fineweb-edu的中文版数据集,但这个数据集没有细分的小子集,该数据集大小达到了600G左右,有资源的读者可以尝试使用这个数据集来预训练一个中文模型。

    修改dataloader

    我们根据我们新下载的数据集重新编写dataloader:

    python
    import numpy as np
    
    def load_tokens(filename):
        npt = np.load(filename)
        npt = npt.astype(np.int32) # added after video
        ptt = torch.tensor(npt, dtype=torch.long)
        return ptt
    
    class DataLoaderLite:
        def __init__(self, B, T, process_rank, num_processes, split):
            self.B = B
            self.T = T
            self.process_rank = process_rank
            self.num_processes = num_processes
            assert split in {'train', 'val'}
    
            # get the shard filenames
            data_root = "edu_fineweb10B"
            shards = os.listdir(data_root)
            shards = [s for s in shards if split in s]
            shards = sorted(shards)
            shards = [os.path.join(data_root, s) for s in shards]
            self.shards = shards
            assert len(shards) > 0, f"no shards found for split {split}"
            if master_process:
                print(f"found {len(shards)} shards for split {split}")
            self.reset()
    
        def reset(self):
            # state, init at shard zero
            self.current_shard = 0
            self.tokens = load_tokens(self.shards[self.current_shard])
            self.current_position = self.B * self.T * self.process_rank
    
        def next_batch(self):
            B, T = self.B, self.T
            buf = self.tokens[self.current_position : self.current_position+B*T+1]
            x = (buf[:-1]).view(B, T) # inputs
            y = (buf[1:]).view(B, T) # targets
            # advance the position in the tensor
            self.current_position += B * T * self.num_processes
            # if loading the next batch would be out of bounds, advance to next shard
            if self.current_position + (B * T * self.num_processes + 1) > len(self.tokens):
                self.current_shard = (self.current_shard + 1) % len(self.shards)
                self.tokens = load_tokens(self.shards[self.current_shard])
                self.current_position = B * T * self.process_rank
            return x, y
    
    train_loader = DataLoaderLite(B=B, T=T, process_rank=ddp_rank, num_processes=ddp_world_size, split="train")

    训练

    修改训练参数

    我们现在的数据集一共有10e9个token,我们每个batch的大小是2**19,所以我们总共需要19073个step来完整遍历一遍数据集。另外gpt-3的技术报告中提到他们使用375m个token来进行warm up,在我们设定的batch size大小下,也就相当于需要715步来进行warm up,因此修改我们的训练参数:

    python
    max_lr = 6e-4
    min_lr = max_lr * 0.1
    warmup_steps = 715
    max_steps = 19073 # 19,073 steps is ~1 epoch, if data is 10B tokens and batch size 0.5M tokens

    validation、生成采样、Hellaswag验证

    首先简单介绍一下Hellaswag。这是一个选择题验证集,大致思路是判断某个句子是否是题干文本的自然延续,只有当模型认知正确的时候才能作出自然延续。具体涉及到的领域可以查看论文附录中的图表。该验证一个有意思的地方在于错误选项并不是随机sample的,而同样也是语言模型生成的句子,这样的生成方式使语言模型会认为这很难,但是人类却觉得它们很容易,在当时,这是一个很好的benchmark。值得一提的是gpt-2中没有提到使用Hellaswag的验证,但是gpt-3的论文中提到了。另外,Hellaswag验证是一个非常smooth的验证,即使是小型语言模型也会以25%的随机概率开始,而且在早期warm up的阶段也会缓慢的改进(early signal)。 下面给出Hellaswag的实现hellaswag.py:

    python
    """
    Downloads and evaluates HellaSwag in Python.
    https://github.com/rowanz/hellaswag
    
    Example HellaSwag json item:
    
    {"ind": 24, "activity_label": "Roof shingle removal", "ctx_a": "A man is sitting on a roof.", "ctx_b": "he", "ctx": "A man is sitting on a roof. he", "split": "val", "split_type": "indomain", "label": 3, "endings": ["is using wrap to wrap a pair of skis.", "is ripping level tiles off.", "is holding a rubik's cube.", "starts pulling up roofing on a roof."], "source_id": "activitynet~v_-JhWjGDPHMY"}
    
    ind: dataset ID
    activity_label: The ActivityNet or WikiHow label for this example
    context: There are two formats. The full context is in ctx. When the context ends in an (incomplete) noun phrase, like for ActivityNet, this incomplete noun phrase is in ctx_b, and the context up until then is in ctx_a. This can be useful for models such as BERT that need the last sentence to be complete. However, it's never required. If ctx_b is nonempty, then ctx is the same thing as ctx_a, followed by a space, then ctx_b.
    endings: a list of 4 endings. The correct index is given by label (0,1,2, or 3)
    split: train, val, or test.
    split_type: indomain if the activity label is seen during training, else zeroshot
    source_id: Which video or WikiHow article this example came from
    
    gpt2 (124M)
    - eleuther harness reports acc 28.92%, acc_norm 31.14% (multiple choice style)
    - this script: 10042 acc: 0.2859 acc_norm: 0.2955 (completion style)
    
    gpt2-xl (1558M)
    - eleuther harness reports acc 40.04%, acc_norm 50.89% (multiple choice style)
    - this script: 10042 acc: 0.3842 acc_norm: 0.4893 (completion style)
    
    The validation set of HellaSwag has a total of 10,042 examples.
    """
    
    import os
    import json
    import requests
    import tiktoken
    from tqdm import tqdm
    import torch
    import torch.nn as nn
    from torch.nn import functional as F
    from transformers import GPT2LMHeadModel
    
    # -----------------------------------------------------------------------------
    DATA_CACHE_DIR = os.path.join(os.path.dirname(__file__), "hellaswag")
    
    def download_file(url: str, fname: str, chunk_size=1024):
        """Helper function to download a file from a given url"""
        resp = requests.get(url, stream=True)
        total = int(resp.headers.get("content-length", 0))
        with open(fname, "wb") as file, tqdm(
            desc=fname,
            total=total,
            unit="iB",
            unit_scale=True,
            unit_divisor=1024,
        ) as bar:
            for data in resp.iter_content(chunk_size=chunk_size):
                size = file.write(data)
                bar.update(size)
    
    hellaswags = {
        "train": "https://raw.githubusercontent.com/rowanz/hellaswag/master/data/hellaswag_train.jsonl",
        "val": "https://raw.githubusercontent.com/rowanz/hellaswag/master/data/hellaswag_val.jsonl",
        "test": "https://raw.githubusercontent.com/rowanz/hellaswag/master/data/hellaswag_test.jsonl",
    }
    
    enc = tiktoken.get_encoding("gpt2")
    
    def download(split):
        """Downloads HellaSwag DATA_CACHE_DIR"""
        os.makedirs(DATA_CACHE_DIR, exist_ok=True)
        data_url = hellaswags[split]
        data_filename = os.path.join(DATA_CACHE_DIR, f"hellaswag_{split}.jsonl")
        if not os.path.exists(data_filename):
            print(f"Downloading {data_url} to {data_filename}...")
            download_file(data_url, data_filename)
    
    def render_example(example):
        """
        Given the example as a dictionary, render it as three torch tensors:
        - tokens (the tokens of context + completion, of size 4xN, as there are always 4 candidates)
        - mask (is 1 in the region of the candidate completion, where we evaluate likelihoods)
        - label (the index of the correct completion, which we hope has the highest likelihood)
        """
        ctx = example["ctx"]
        label = example["label"]
        endings = example["endings"]
    
        # data needed to reproduce this eval on the C size
        data = {
            "label": label,
            "ctx_tokens": None,
            "ending_tokens": [],
        }
    
        # gather up all the tokens
        ctx_tokens = enc.encode(ctx)
        data["ctx_tokens"] = ctx_tokens
        tok_rows = []
        mask_rows = []
        for end in endings:
            end_tokens = enc.encode(" " + end) # note: prepending " " because GPT-2 tokenizer
            tok_rows.append(ctx_tokens + end_tokens)
            mask_rows.append([0]*len(ctx_tokens) + [1]*len(end_tokens))
            data["ending_tokens"].append(end_tokens)
    
        # have to be careful during the collation because the number of tokens in each row can differ
        max_len = max(len(row) for row in tok_rows)
        tokens = torch.zeros((4, max_len), dtype=torch.long)
        mask = torch.zeros((4, max_len), dtype=torch.long)
        for i, (tok_row, mask_row) in enumerate(zip(tok_rows, mask_rows)):
            tokens[i, :len(tok_row)] = torch.tensor(tok_row)
            mask[i, :len(mask_row)] = torch.tensor(mask_row)
    
        return data, tokens, mask, label
    
    def iterate_examples(split):
        # there are 10,042 examples in total in val
        download(split)
        with open(os.path.join(DATA_CACHE_DIR, f"hellaswag_{split}.jsonl"), "r") as f:
            for line in f:
                example = json.loads(line)
                yield example
    
    @torch.no_grad()
    def evaluate(model_type, device):
    
        torch.set_float32_matmul_precision('high') # use tf32
        model = GPT2LMHeadModel.from_pretrained(model_type)
        model.to(device)
        # model = torch.compile(model) # optionally torch compile the model
    
        num_correct_norm = 0
        num_correct = 0
        num_total = 0
        for example in iterate_examples("val"):
            data, tokens, mask, label = render_example(example)
            tokens = tokens.to(device)
            mask = mask.to(device)
    
            # get the logits
            logits = model(tokens).logits
            # evaluate the autoregressive loss at all positions
            shift_logits = (logits[..., :-1, :]).contiguous()
            shift_tokens = (tokens[..., 1:]).contiguous()
            flat_shift_logits = shift_logits.view(-1, shift_logits.size(-1))
            flat_shift_tokens = shift_tokens.view(-1)
            shift_losses = F.cross_entropy(flat_shift_logits, flat_shift_tokens, reduction='none')
            shift_losses = shift_losses.view(tokens.size(0), -1)
            # now get the average loss just for the completion region (where mask == 1), in each row
            shift_mask = (mask[..., 1:]).contiguous() # we must shift mask, so we start at the last prompt token
            masked_shift_losses = shift_losses * shift_mask
            # sum and divide by the number of 1s in the mask
            sum_loss = masked_shift_losses.sum(dim=1)
            avg_loss = sum_loss / shift_mask.sum(dim=1)
            # now we have a loss for each of the 4 completions
            # the one with the lowest loss should be the most likely
            pred = sum_loss.argmin().item()
            pred_norm = avg_loss.argmin().item()
    
            # accumulate stats
            num_total += 1
            num_correct += int(pred == label)
            num_correct_norm += int(pred_norm == label)
            print(f"{num_total} acc_norm: {num_correct_norm}/{num_total}={num_correct_norm/num_total:.4f}")
    
            # debug: pretty print a few examples, and the losses in each case
            if num_total < 10:
                print("---")
                print(f"Context:\n {example['ctx']}")
                print(f"Endings:")
                for i, end in enumerate(example["endings"]):
                    print(f"{i} (loss: {avg_loss[i].item():.4f}) {end}")
                print(f"predicted: {pred_norm}, actual: {label}")
    
    if __name__ == "__main__":
        import argparse
        parser = argparse.ArgumentParser()
        parser.add_argument("-m", "--model_type", type=str, default="gpt2", help="the model type to use")
        parser.add_argument("-d", "--device", type=str, default="cuda", help="the device to use")
        args = parser.parse_args()
        evaluate(args.model_type, args.device)

    接下来给出上述修改的代码

    python
    from hellaswag import render_example, iterate_examples
    
    enc = tiktoken.get_encoding("gpt2")
    
    # added after video, pytorch can be serious about it's device vs. device_type distinction
    device_type = "cuda" if device.startswith("cuda") else "cpu"
    
    # 该参数后面要用
    use_compile = True
    if use_compile:
        model = torch.compile(model)
    
    # 加载一个validation loader用于validate
    train_loader = DataLoaderLite(B=B, T=T, process_rank=ddp_rank, num_processes=ddp_world_size, split="train")
    val_loader = DataLoaderLite(B=B, T=T, process_rank=ddp_rank, num_processes=ddp_world_size, split="val")
    
    # 创建log
    # create the log directory we will write checkpoints to and log to
    log_dir = "log"
    os.makedirs(log_dir, exist_ok=True)
    log_file = os.path.join(log_dir, f"log.txt")
    with open(log_file, "w") as f: # open for writing to clear the file
        pass
    
    # Hellaswag的评估
    def get_most_likely_row(tokens, mask, logits):
        # evaluate the autoregressive loss at all positions
        shift_logits = (logits[..., :-1, :]).contiguous()
        shift_tokens = (tokens[..., 1:]).contiguous()
        flat_shift_logits = shift_logits.view(-1, shift_logits.size(-1))
        flat_shift_tokens = shift_tokens.view(-1)
        shift_losses = F.cross_entropy(flat_shift_logits, flat_shift_tokens, reduction='none')
        shift_losses = shift_losses.view(tokens.size(0), -1)
        # now get the average loss just for the completion region (where mask == 1), in each row
        shift_mask = (mask[..., 1:]).contiguous() # we must shift mask, so we start at the last prompt token
        masked_shift_losses = shift_losses * shift_mask
        # sum and divide by the number of 1s in the mask
        sum_loss = masked_shift_losses.sum(dim=1)
        avg_loss = sum_loss / shift_mask.sum(dim=1)
        # now we have a loss for each of the 4 completions
        # the one with the lowest loss should be the most likely
        pred_norm = avg_loss.argmin().item()
        return pred_norm
    
    # 主循环
    for step in range(max_steps):
        t0 = time.time()
        last_step = (step == max_steps - 1)
    
        # once in a while evaluate our validation loss
        if step % 250 == 0 or last_step:
            model.eval()
            val_loader.reset()
            with torch.no_grad():
                val_loss_accum = 0.0
                val_loss_steps = 20
                for _ in range(val_loss_steps):
                    x, y = val_loader.next_batch()
                    x, y = x.to(device), y.to(device)
                    with torch.autocast(device_type=device_type, dtype=torch.bfloat16):
                        logits, loss = model(x, y)
                    loss = loss / val_loss_steps
                    val_loss_accum += loss.detach()
            if ddp:
                dist.all_reduce(val_loss_accum, op=dist.ReduceOp.AVG)
            if master_process:
                print(f"validation loss: {val_loss_accum.item():.4f}")
                with open(log_file, "a") as f:
                    f.write(f"{step} val {val_loss_accum.item():.4f}\n")
                if step > 0 and (step % 5000 == 0 or last_step):
                    # optionally write model checkpoints
                    checkpoint_path = os.path.join(log_dir, f"model_{step:05d}.pt")
                    checkpoint = {
                        'model': raw_model.state_dict(),
                        'config': raw_model.config,
                        'step': step,
                        'val_loss': val_loss_accum.item()
                    }
                    # you might also want to add optimizer.state_dict() and
                    # rng seeds etc., if you wanted to more exactly resume training
                    torch.save(checkpoint, checkpoint_path)
    
        # once in a while evaluate hellaswag
        if (step % 250 == 0 or last_step) and (not use_compile):
            num_correct_norm = 0
            num_total = 0
            for i, example in enumerate(iterate_examples("val")):
                # only process examples where i % ddp_world_size == ddp_rank
                if i % ddp_world_size != ddp_rank:
                    continue
                # render the example into tokens and labels
                _, tokens, mask, label = render_example(example)
                tokens = tokens.to(device)
                mask = mask.to(device)
                # get the logits
                with torch.no_grad():
                    with torch.autocast(device_type=device_type, dtype=torch.bfloat16):
                        logits, loss = model(tokens)
                    pred_norm = get_most_likely_row(tokens, mask, logits)
                num_total += 1
                num_correct_norm += int(pred_norm == label)
            # reduce the stats across all processes
            if ddp:
                num_total = torch.tensor(num_total, dtype=torch.long, device=device)
                num_correct_norm = torch.tensor(num_correct_norm, dtype=torch.long, device=device)
                dist.all_reduce(num_total, op=dist.ReduceOp.SUM)
                dist.all_reduce(num_correct_norm, op=dist.ReduceOp.SUM)
                num_total = num_total.item()
                num_correct_norm = num_correct_norm.item()
            acc_norm = num_correct_norm / num_total
            if master_process:
                print(f"HellaSwag accuracy: {num_correct_norm}/{num_total}={acc_norm:.4f}")
                with open(log_file, "a") as f:
                    f.write(f"{step} hella {acc_norm:.4f}\n")
    
        # once in a while generate from the model (except step 0, which is noise)
        # 在这里Karpathy说使用torch.compile之后generate会有bug,因此这里使用这个方法来避免generate samples
        if ((step > 0 and step % 250 == 0) or last_step) and (not use_compile):
            model.eval()
            num_return_sequences = 4
            max_length = 32
            tokens = enc.encode("Hello, I'm a language model,")
            tokens = torch.tensor(tokens, dtype=torch.long)
            tokens = tokens.unsqueeze(0).repeat(num_return_sequences, 1)
            xgen = tokens.to(device)
            sample_rng = torch.Generator(device=device)
            sample_rng.manual_seed(42 + ddp_rank)
            while xgen.size(1) < max_length:
                # forward the model to get the logits
                with torch.no_grad():
                    with torch.autocast(device_type=device_type, dtype=torch.bfloat16):
                        logits, loss = model(xgen) # (B, T, vocab_size)
                    # take the logits at the last position
                    logits = logits[:, -1, :] # (B, vocab_size)
                    # get the probabilities
                    probs = F.softmax(logits, dim=-1)
                    # do top-k sampling of 50 (huggingface pipeline default)
                    # topk_probs here becomes (5, 50), topk_indices is (5, 50)
                    topk_probs, topk_indices = torch.topk(probs, 50, dim=-1)
                    # select a token from the top-k probabilities
                    # note: multinomial does not demand the input to sum to 1
                    ix = torch.multinomial(topk_probs, 1, generator=sample_rng) # (B, 1)
                    # gather the corresponding indices
                    xcol = torch.gather(topk_indices, -1, ix) # (B, 1)
                    # append to the sequence
                    xgen = torch.cat((xgen, xcol), dim=1)
            # print the generated text
            for i in range(num_return_sequences):
                tokens = xgen[i, :max_length].tolist()
                decoded = enc.decode(tokens)
                print(f"rank {ddp_rank} sample {i}: {decoded}")
    
        # do one step of the optimization
        model.train()
        optimizer.zero_grad()
        loss_accum = 0.0
        for micro_step in range(grad_accum_steps):
            x, y = train_loader.next_batch()
            x, y = x.to(device), y.to(device)
            # added after video, this field is also used by the forward pass.
            if ddp:
                model.require_backward_grad_sync = (micro_step == grad_accum_steps - 1)
            with torch.autocast(device_type=device_type, dtype=torch.bfloat16):
                logits, loss = model(x, y)
            # we have to scale the loss to account for gradient accumulation,
            # because the gradients just add on each successive backward().
            # addition of gradients corresponds to a SUM in the objective, but
            # instead of a SUM we want MEAN. Scale the loss here so it comes out right
            loss = loss / grad_accum_steps
            loss_accum += loss.detach()
            loss.backward()
        if ddp:
            dist.all_reduce(loss_accum, op=dist.ReduceOp.AVG)
        norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        # determine and set the learning rate for this iteration
        lr = get_lr(step)
        for param_group in optimizer.param_groups:
            param_group['lr'] = lr
        optimizer.step()
        if device_type == "cuda":
            torch.cuda.synchronize() # wait for the GPU to finish work
        t1 = time.time()
        dt = t1 - t0 # time difference in seconds
        tokens_processed = train_loader.B * train_loader.T * grad_accum_steps * ddp_world_size
        tokens_per_sec = tokens_processed / dt
        if master_process:
            print(f"step {step:5d} | loss: {loss_accum.item():.6f} | lr {lr:.4e} | norm: {norm:.4f} | dt: {dt*1000:.2f}ms | tok/sec: {tokens_per_sec:.2f}")
            with open(log_file, "a") as f:
                f.write(f"{step} train {loss_accum.item():.6f}\n")

    至此为止,我们就可以训练这个模型啦!接下来只需要静待训练完成即可

    模型查看

    我在两张RTX3090 24G上训练了1个epoch,花费了24小时,最终得到我的模型。首先打印出模型的形状:

    bash
    GPT(
      (transformer): ModuleDict(
        (wte): Embedding(50304, 768)
        (wpe): Embedding(1024, 768)
        (h): ModuleList(
          (0-11): 12 x Block(
            (ln_1): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
            (attn): CausalSelfAttention(
              (c_attn): Linear(in_features=768, out_features=2304, bias=True)
              (c_proj): Linear(in_features=768, out_features=768, bias=True)
            )
            (ln_2): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
            (mlp): MLP(
              (c_fc): Linear(in_features=768, out_features=3072, bias=True)
              (gelu): GELU(approximate='tanh')
              (c_proj): Linear(in_features=3072, out_features=768, bias=True)
            )
          )
        )
        (ln_f): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
      )
      (lm_head): Linear(in_features=768, out_features=50304, bias=False)
    )

    然后给出模型的训练损失:

    最终给出我模型的一组生成结果:

    python
    def generate(model, prompt, max_length=30, num_return_sequences=5, device="cuda"):
        enc = tiktoken.get_encoding("gpt2")
        tokens = enc.encode(prompt)
        tokens = torch.tensor(tokens, dtype=torch.long)
        tokens = tokens.unsqueeze(0).repeat(num_return_sequences, 1)
        x = tokens.to( device)
        
        while x.size(1) < max_length:
            with torch.no_grad():
                logits, _ = model(x)
                logits = logits[:, -1, :]
                probs = F.softmax(logits, dim=-1)
                topk_probs, topk_ids = torch.topk(probs, 50, dim=-1)
                ix = torch.multinomial(topk_probs, num_samples=1)
                xcol = topk_ids.gather(1, ix)
                x = torch.cat((x, xcol), dim=1)
                
        results = []
        for i in range(num_return_sequences):
            tokens = x[i, :max_length].tolist()
            decoded = enc.decode(tokens)
            results.append(decoded)
            
        return results
    
    sentences = generate(model, "Hello! I'm a language model", max_length=64)
    for sentence in sentences:
        print("> ", sentence)
    bash
    >  Hello! I'm a language model grader and you're not a software developer myself, and I'm not an architect. So I've done a master of architecture with a few other architects and a few software engineers before coming back to my house. Your question is, Do you plan to apply the architectural elements of the
    >  Hello! I'm a language modeler in Google Earth," she said. "Before, I had to teach my kids to talk, write, and share ideas."
    "I think it's probably too much. I've gotten more practice with kids over my years in science classes," he said. "The more kids
    >  Hello! I'm a language modeler. I believe you won't find me as a person who has studied math and who has been able to understand that in the past. I just wish I could find more examples, and if you think I know what you want to do I'll help.
    When my mother was
    >  Hello! I'm a language model student…this year I'm a full time education instructor and I always write courses and I am a good teacher for most of the students. I also take lessons at home or abroad. After my freshman year, I had to learn a few languages and I learned many words and phrases in
    >  Hello! I'm a language modeler with very little knowledge of computers (I'd be pleased to know a little bit more about Google). To say this about me is pretty much a shame at this point because the basic terms used in Google's data model include “Data Set” itself, “View�

    到此为止,我们就完整的跑通了整个预训练流程啦!恭喜!不过我们的模型还是太小了,想要获取更好的效果可以考虑使用更大的模型架构参数和更多的token,后续我也会跟进这方面的工作并在我训练出更大的模型后加入SFT和RLHF的内容。

    下一篇从零构建GPT-2(三)

    评论

    登录 后参与评论

    还没有评论,来说点什么吧

    从零构建GPT-24 篇

    1. 01从零构建GPT-2(一)
    2. 02从零构建GPT-2(二)
    3. 03从零构建GPT-2(三)
    4. 04从零构建GPT-2(四)

    // 目录