MCPcopy Create free account
hub / github.com/boyiwei/alignment-attribution-code / eval_ppl_wikitext_train

Function eval_ppl_wikitext_train

lib/eval.py:100–150  ·  view source on GitHub ↗
(model, trainloader, bs=1, device=None)

Source from the content-addressed store, hash-verified

98
99# Function to evaluate perplexity (ppl) specifically on the wikitext dataset
100def eval_ppl_wikitext_train(model, trainloader, bs=1, device=None):
101 # Get input IDs
102 # testenc = testenc.input_ids
103
104 # Calculate number of samples
105 # nsamples = testenc.numel() // model.seqlen
106 nsamples = len(trainloader)
107
108 # List to store negative log likelihoods
109 nlls = []
110 print(f"nsamples {nsamples}")
111
112 # Loop through each batch
113 for i in range(0, nsamples, bs):
114 if i % 50 == 0:
115 print(f"sample {i}")
116
117 # Calculate end index
118 j = min(i + bs, nsamples)
119
120 # Prepare inputs and move to device
121 # inputs = testenc[:,(i * model.seqlen):(j * model.seqlen)].to(device)
122 inputs = trainloader[i][0].to(device)
123 inputs = inputs.reshape(j - i, model.seqlen)
124
125 # Forward pass through the model
126 lm_logits = model(inputs).logits
127
128 # Shift logits and labels for next token prediction
129 shift_logits = lm_logits[:, :-1, :].contiguous()
130 shift_labels = inputs[:, 1:]
131
132 # Compute loss
133 loss_fct = nn.CrossEntropyLoss()
134 loss = loss_fct(
135 shift_logits.reshape(-1, shift_logits.size(-1)), shift_labels.reshape(-1)
136 )
137
138 # Calculate negative log likelihood
139 neg_log_likelihood = loss.float() * model.seqlen * (j - i)
140
141 # Append to list of negative log likelihoods
142 nlls.append(neg_log_likelihood)
143
144 # Compute perplexity
145 ppl = torch.exp(torch.stack(nlls).sum() / (nsamples * model.seqlen))
146
147 # Empty CUDA cache to save memory
148 torch.cuda.empty_cache()
149
150 return ppl.item()
151
152
153# Function to evaluate perplexity (ppl) specifically on the wikitext dataset

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected