File size: 10,065 Bytes
d91766b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import json
import math
import os
import random
import time
import numpy as np
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader, DistributedSampler
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModel
from peft import PeftModel
from generate import generate
from countdown import CTDDataset
from sudoku import SudokuDataset
DATASET_MAP = {
"countdown": CTDDataset,
"sudoku": SudokuDataset,
}
def init_seed(seed):
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
def setup_ddp():
dist.init_process_group("nccl")
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
return local_rank
def cleanup_ddp():
dist.destroy_process_group()
def evaluate(
model,
tokenizer,
dataloader,
gen_length=128,
temperature=0.0,
cfg_scale=0.0,
steps=64,
block_length=32,
filename=None,
remasking="low_confidence",
):
model.eval()
total_processed = torch.tensor(0, device=model.device)
wall_times = []
all_generations = []
device = model.device
for batch in tqdm(dataloader, disable=(dist.get_rank() != 0)):
start_time = time.time()
input_ids = batch["input_ids"].to(device)
gt_answers = batch["answers"]
questions = batch["questions"]
prompts = batch["prompts"]
out = generate(
model,
input_ids,
tokenizer,
steps=steps,
gen_length=gen_length,
block_length=block_length,
temperature=temperature,
cfg_scale=cfg_scale,
remasking=remasking, #"low_confidence",
)
generated_texts = tokenizer.batch_decode(out[:, -gen_length:], skip_special_tokens=False)
example_result = [
{
"question": questions[j],
"prompt_input": prompts[j],
"generations": generated_texts[j],
"ground_truth": gt_answers[j],
"nfes": steps,
}
for j in range(len(gt_answers))
]
all_generations.extend(example_result)
total_processed += len(generated_texts)
wall_times.append(time.time() - start_time)
# Print individual results
# if dist.get_rank() == 0:
# idx = random.randint(0, len(questions) - 1)
# print(f"Question: {questions[idx]}")
# print("-" * 50)
# print("Generation:")
# print(generated_texts[idx])
# print("-" * 50)
# print(f"Ground truth: {gt_answers[idx]}")
avg_wall_time = sum(wall_times) / len(wall_times)
metrics = {
"wall_time": avg_wall_time,
"generations": all_generations,
"total_processed": total_processed.item(),
}
return metrics
class CustomDistributedSampler(DistributedSampler):
"""
From torch docs:
drop_last (bool, optional): if ``True``, then the sampler will drop the
tail of the data to make it evenly divisible across the number of
replicas. If ``False``, the sampler will add extra indices to make
the data evenly divisible across the replicas
We want drop_last = False, but don't want to have extra padding indices. Hence using a custom sampler.
"""
def __init__(
self,
dataset,
num_replicas=None,
rank=None,
shuffle=True,
seed=0,
drop_last=False,
) -> None:
if num_replicas is None:
if not dist.is_available():
raise RuntimeError("Requires distributed package to be available")
num_replicas = dist.get_world_size()
if rank is None:
if not dist.is_available():
raise RuntimeError("Requires distributed package to be available")
rank = dist.get_rank()
if rank >= num_replicas or rank < 0:
raise ValueError(f"Invalid rank {rank}, rank should be in the interval [0, {num_replicas - 1}]")
self.dataset = dataset
self.num_replicas = num_replicas
self.rank = rank
self.epoch = 0
self.drop_last = drop_last
if self.drop_last and len(self.dataset) % self.num_replicas != 0:
self.num_samples = math.ceil((len(self.dataset) - self.num_replicas) / self.num_replicas)
self.total_size = self.num_samples * self.num_replicas
else:
# If we don't drop the last batch, we need to calculate the number of samples per rank.
self.total_size = len(self.dataset)
self.num_samples = len(self.dataset) // self.num_replicas + int(
rank < (self.total_size % self.num_replicas)
)
self.shuffle = shuffle
self.seed = seed
if __name__ == "__main__":
init_seed(42)
# Note: This evaluation script saves only model generations. A separate parser is used later to extract
# predictions and calculate metrics.
local_rank = setup_ddp()
parser = argparse.ArgumentParser()
parser.add_argument("--model_path", type=str, default="/data1/shared/LLaDA-8B-Instruct/")
parser.add_argument("--few_shot", type=int, default=0)
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument(
"--dataset", type=str, choices=["gsm8k", "math", "countdown", "sudoku", "game24"], default="gsm8k"
)
parser.add_argument("--suffix", type=str, default="")
parser.add_argument("--checkpoint_path", type=str, default="")
parser.add_argument("--gen_length", type=int, default=128)
parser.add_argument("--block_length", type=int, default=32)
parser.add_argument("--diffusion_steps", type=int, default=64)
parser.add_argument("--add_reasoning", action="store_true")
parser.add_argument("--dont_save", action="store_true")
parser.add_argument("--output_dir", type=str, default="results/")
parser.add_argument("--dont_use_box", action="store_true")
parser.add_argument("--temperature", type=float, default=0.0)
parser.add_argument("--remasking", type=str, default="low_confidence")
parser.add_argument("--seed", type=int, default=None)
args = parser.parse_args()
if args.seed is not None:
init_seed(args.seed)
# args.diffusion_steps = args.gen_length // 2
# num_evals = {"gsm8k": -1, "math": 2, "countdown": 256, "sudoku": 256}
num_evals = {"gsm8k": -1, "math": -1, "countdown": 256, "sudoku": 256}
if len(args.checkpoint_path):
model_name = args.checkpoint_path.split("/")
model_name = model_name[-2] + "_" + model_name[-1]
else:
model_name = "instruct" if "Instruct" in args.model_path else "base"
if args.few_shot > 0:
model_name = model_name + f"_fs{args.few_shot}"
if len(args.suffix) > 0:
model_name = model_name + f"_{args.suffix}"
os.makedirs(args.output_dir, exist_ok=True)
filename = f"{args.output_dir}/{args.dataset}_{model_name}_{args.gen_length}_{args.diffusion_steps}_{dist.get_rank()}_generations.json"
filename_0 = f"{args.output_dir}/{args.dataset}_{model_name}_{args.gen_length}_{args.diffusion_steps}_0_generations.json"
# if the file already exists, directly exit
if os.path.exists(filename):
print(f"File {filename} already exists, exiting")
cleanup_ddp()
import sys
sys.exit(0)
elif os.path.exists(filename_0):
print(f"The rank 0 file {filename_0} already exists, exiting")
cleanup_ddp()
import sys
sys.exit(0)
model = AutoModel.from_pretrained(args.model_path, trust_remote_code=True, torch_dtype=torch.bfloat16).to(
local_rank
)
tokenizer = AutoTokenizer.from_pretrained(args.model_path, trust_remote_code=True)
if args.checkpoint_path:
model = PeftModel.from_pretrained(model, args.checkpoint_path, torch_dtype=torch.bfloat16).to(
local_rank
)
if dist.get_world_size() > 1:
dist.barrier() # Make sure all processes are ready
for param in model.parameters():
dist.broadcast(param.data, src=0)
print(f"Rank {local_rank}: Parameters synchronized")
dataset = DATASET_MAP[args.dataset](
tokenizer,
subsample=num_evals[args.dataset],
num_examples=args.few_shot,
add_reasoning=True, # prefill for all models
)
dataloader = DataLoader(
dataset,
batch_size=args.batch_size,
sampler=CustomDistributedSampler(dataset, shuffle=False),
collate_fn=dataset.collate_fn,
)
print(f"Saving generations to {filename}")
metrics = evaluate(
model,
tokenizer,
dataloader,
gen_length=args.gen_length,
block_length=args.block_length,
steps=args.diffusion_steps,
temperature=args.temperature,
filename=filename,
remasking=args.remasking,
)
if not args.dont_save:
with open(filename, "w") as f:
json.dump(
{
"generations": metrics["generations"],
"metrics": {
"wall_time": metrics["wall_time"],
"total_processed": metrics["total_processed"],
},
"model_path": args.model_path,
"checkpoint_path": args.checkpoint_path,
"gen_length": args.gen_length,
"diffusion_steps": args.diffusion_steps,
"block_length": args.block_length,
},
f,
indent=2,
)
cleanup_ddp()
|