MCPcopy Create free account
hub / github.com/OpenGVLab/EfficientQAT / test_ppl

Function test_ppl

datautils_block.py:173–229  ·  view source on GitHub ↗
(model, tokenizer, datasets=['wikitext2'],ppl_seqlen=2048)

Source from the content-addressed store, hash-verified

171
172@torch.no_grad()
173def test_ppl(model, tokenizer, datasets=['wikitext2'],ppl_seqlen=2048):
174 results = {}
175 for dataset in datasets:
176 testloader = get_loaders(
177 dataset,
178 tokenizer,
179 seed=0,
180 seqlen=ppl_seqlen,
181 test_only=True
182 )
183 if "c4" in dataset:
184 testenc = testloader
185 else:
186 testenc = testloader.input_ids
187
188 seqlen = ppl_seqlen
189 nsamples = testenc.numel() // seqlen
190 use_cache = model.config.use_cache
191 model.config.use_cache = False
192 model.eval()
193 nlls = []
194 if hasattr(model,'lm_head') and isinstance(model.lm_head, nn.Linear):
195 classifier = model.lm_head
196 elif hasattr(model.model,'lm_head'):
197 # for gptqmodels
198 classifier = None
199 elif hasattr(model,'output'):
200 # for internlm
201 classifier = model.output
202 else:
203 raise NotImplementedError
204 for i in tqdm(range(nsamples)):
205 batch = testenc[:, (i * seqlen) : ((i + 1) * seqlen)].to(model.device)
206 outputs = model.model(batch)
207 if classifier is not None:
208 hidden_states = outputs[0]
209 logits = classifier(hidden_states.to(classifier.weight.dtype))
210 else:
211 logits = outputs[0]
212 shift_logits = logits[:, :-1, :]
213 shift_labels = testenc[:, (i * seqlen) : ((i + 1) * seqlen)][
214 :, 1:
215 ].to(shift_logits.device)
216 loss_fct = nn.CrossEntropyLoss()
217 loss = loss_fct(
218 shift_logits.view(-1, shift_logits.size(-1)),
219 shift_labels.view(-1),
220 )
221 neg_log_likelihood = loss.float() * seqlen
222 nlls.append(neg_log_likelihood)
223
224
225 ppl = torch.exp(torch.stack(nlls).sum() / (nsamples * seqlen))
226 print(f'{dataset}:{ppl}')
227 results[dataset] = ppl.item()
228 model.config.use_cache = use_cache
229 return results
230

Callers 4

evaluateFunction · 0.90
on_evaluateMethod · 0.90
mainFunction · 0.90
mainFunction · 0.90

Calls 1

get_loadersFunction · 0.85

Tested by

no test coverage detected