|
| 1 | +import utils |
| 2 | +import model_utils |
| 3 | +import quant_utils |
| 4 | +import torch |
| 5 | +import os |
| 6 | +import logging |
| 7 | +from tqdm import tqdm |
| 8 | + |
| 9 | + |
| 10 | +@torch.no_grad() |
| 11 | +def evaluator(model, testenc, dev, args): |
| 12 | + |
| 13 | + model.eval() |
| 14 | + |
| 15 | + if 'opt' in args.model: |
| 16 | + opt_type = True |
| 17 | + llama_type = False |
| 18 | + elif 'meta' in args.model: |
| 19 | + llama_type = True |
| 20 | + opt_type = False |
| 21 | + else: |
| 22 | + raise ValueError(f'Unknown model {args.model}') |
| 23 | + |
| 24 | + |
| 25 | + use_cache = model.config.use_cache |
| 26 | + model.config.use_cache = False |
| 27 | + |
| 28 | + if opt_type: |
| 29 | + layers = model.model.decoder.layers |
| 30 | + model.model.decoder.embed_tokens = model.model.decoder.embed_tokens.to(dev) |
| 31 | + model.model.decoder.embed_positions = model.model.decoder.embed_positions.to(dev) |
| 32 | + if hasattr(model.model.decoder, 'project_out') and model.model.decoder.project_out: |
| 33 | + model.model.decoder.project_out = model.model.decoder.project_out.to(dev) |
| 34 | + if hasattr(model.model.decoder, 'project_in') and model.model.decoder.project_in: |
| 35 | + model.model.decoder.project_in = model.model.decoder.project_in.to(dev) |
| 36 | + |
| 37 | + elif llama_type: |
| 38 | + layers = model.model.layers |
| 39 | + model.model.embed_tokens = model.model.embed_tokens.to(dev) |
| 40 | + |
| 41 | + layers[0] = layers[0].to(dev) |
| 42 | + |
| 43 | + # Convert the whole text of evaluation dataset into batches of sequences. |
| 44 | + input_ids = testenc.input_ids # (1, text_len) |
| 45 | + nsamples = input_ids.numel() // model.seqlen # The tail is truncated. |
| 46 | + input_ids = input_ids[:, :nsamples * model.seqlen].view(nsamples, model.seqlen).to(dev) # (nsamples, seqlen) |
| 47 | + |
| 48 | + batch_size = args.bsz |
| 49 | + input_ids = [input_ids[i:i + batch_size] for i in range(0, nsamples, batch_size)] |
| 50 | + nbatches = len(input_ids) |
| 51 | + |
| 52 | + dtype = next(iter(model.parameters())).dtype |
| 53 | + # The input of the first decoder layer. |
| 54 | + inps = torch.zeros( |
| 55 | + (nbatches, batch_size, model.seqlen, model.config.hidden_size), dtype=dtype, device=dev |
| 56 | + ) |
| 57 | + inps = [0] * nbatches |
| 58 | + cache = {'i': 0, 'attention_mask': None} |
| 59 | + class Catcher(torch.nn.Module): |
| 60 | + def __init__(self, module): |
| 61 | + super().__init__() |
| 62 | + self.module = module |
| 63 | + def forward(self, inp, **kwargs): |
| 64 | + inps[cache['i']] = inp |
| 65 | + cache['i'] += 1 |
| 66 | + cache['attention_mask'] = kwargs['attention_mask'] |
| 67 | + if llama_type: |
| 68 | + cache['position_ids'] = kwargs['position_ids'] |
| 69 | + raise ValueError |
| 70 | + layers[0] = Catcher(layers[0]) |
| 71 | + |
| 72 | + for i in range(nbatches): |
| 73 | + batch = input_ids[i] |
| 74 | + try: |
| 75 | + model(batch) |
| 76 | + except ValueError: |
| 77 | + pass |
| 78 | + layers[0] = layers[0].module |
| 79 | + layers[0] = layers[0].cpu() |
| 80 | + |
| 81 | + if opt_type: |
| 82 | + model.model.decoder.embed_tokens = model.model.decoder.embed_tokens.cpu() |
| 83 | + model.model.decoder.embed_positions = model.model.decoder.embed_positions.cpu() |
| 84 | + if hasattr(model.model.decoder, 'project_out') and model.model.decoder.project_out: |
| 85 | + model.model.decoder.project_out = model.model.decoder.project_out.cpu() |
| 86 | + if hasattr(model.model.decoder, 'project_in') and model.model.decoder.project_in: |
| 87 | + model.model.decoder.project_in = model.model.decoder.project_in.cpu() |
| 88 | + elif llama_type: |
| 89 | + model.model.embed_tokens = model.model.embed_tokens.cpu() |
| 90 | + position_ids = cache['position_ids'] |
| 91 | + |
| 92 | + torch.cuda.empty_cache() |
| 93 | + outs = [0] * nbatches |
| 94 | + attention_mask = cache['attention_mask'] |
| 95 | + |
| 96 | + for i in tqdm(range(len(layers)), desc="(Eval) Layers"): |
| 97 | + layer = layers[i].to(dev) |
| 98 | + |
| 99 | + # Dump the layer input and output |
| 100 | + if args.capture_layer_io and args.layer_idx == i: |
| 101 | + captured_io = model_utils.capture_layer_io(model_utils.get_model_type(model), layer, inps) |
| 102 | + save_path = model_utils.get_layer_io_save_path(args) |
| 103 | + os.makedirs(os.path.dirname(save_path), exist_ok=True) |
| 104 | + torch.save(captured_io, save_path) |
| 105 | + logging.info(f'Dumped layer input and output to: {save_path}') |
| 106 | + |
| 107 | + for j in range(nbatches): |
| 108 | + if opt_type: |
| 109 | + outs[j] = layer(inps[j], attention_mask=attention_mask)[0] |
| 110 | + elif llama_type: |
| 111 | + outs[j] = layer(inps[j], attention_mask=attention_mask, position_ids=position_ids)[0] |
| 112 | + layers[i] = layer.cpu() |
| 113 | + del layer |
| 114 | + torch.cuda.empty_cache() |
| 115 | + inps, outs = outs, inps |
| 116 | + |
| 117 | + if opt_type: |
| 118 | + if model.model.decoder.final_layer_norm is not None: |
| 119 | + model.model.decoder.final_layer_norm = model.model.decoder.final_layer_norm.to(dev) |
| 120 | + if model.model.decoder.project_out is not None: |
| 121 | + model.model.decoder.project_out = model.model.decoder.project_out.to(dev) |
| 122 | + |
| 123 | + elif llama_type: |
| 124 | + if model.model.norm is not None: |
| 125 | + model.model.norm = model.model.norm.to(dev) |
| 126 | + |
| 127 | + model.lm_head = model.lm_head.to(dev) |
| 128 | + nlls = [] |
| 129 | + loss_fct = torch.nn.CrossEntropyLoss(reduction = "none") |
| 130 | + for i in range(nbatches): |
| 131 | + hidden_states = inps[i] |
| 132 | + if opt_type: |
| 133 | + if model.model.decoder.final_layer_norm is not None: |
| 134 | + hidden_states = model.model.decoder.final_layer_norm(hidden_states) |
| 135 | + if model.model.decoder.project_out is not None: |
| 136 | + hidden_states = model.model.decoder.project_out(hidden_states) |
| 137 | + elif llama_type: |
| 138 | + if model.model.norm is not None: |
| 139 | + hidden_states = model.model.norm(hidden_states) |
| 140 | + lm_logits = model.lm_head(hidden_states) |
| 141 | + shift_logits = lm_logits[:, :-1, :] |
| 142 | + shift_labels = input_ids[i][:, 1:] |
| 143 | + loss = loss_fct(shift_logits.permute(0, 2, 1), shift_labels) |
| 144 | + neg_log_likelihood = loss.float().mean(dim=1) |
| 145 | + nlls.append(neg_log_likelihood) |
| 146 | + nlls_tensor = torch.cat(nlls) |
| 147 | + ppl = torch.exp(nlls_tensor.mean()) |
| 148 | + model.config.use_cache = use_cache |
| 149 | + logging.info(f'\n{args.eval_dataset.upper()} PPL: {ppl.item():.3f}') |
| 150 | + return ppl.item() |
0 commit comments