{"record":{"id":"01f3f88dee8c3db2","repo":"rohitg00/ai-engineering-from-scratch","slug":"neg-log-probs-must-be-non-negative-did-you-forget","errorCode":null,"errorMessage":"neg_log_probs must be non-negative (did you forget the negation?)","messagePattern":"neg_log_probs must be non-negative \\(did you forget the negation\\?\\)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"phases/19-capstone-projects/73-perplexity-calibration/code/main.py","lineNumber":42,"sourceCode":"    avg_neg_log_likelihood: float\n    total_tokens: int\n\n    def to_dict(self) -> dict:\n        return {\n            \"perplexity\": self.perplexity,\n            \"avg_neg_log_likelihood\": self.avg_neg_log_likelihood,\n            \"total_tokens\": self.total_tokens,\n        }\n\n    @classmethod\n    def from_token_nll(cls, neg_log_probs: Sequence[float], token_counts: Sequence[int]) -> \"PerplexityResult\":\n        if len(neg_log_probs) != len(token_counts):\n            raise ValueError(\"neg_log_probs and token_counts must align\")\n        total_nll = 0.0\n        total_tokens = 0\n        for nll, n in zip(neg_log_probs, token_counts):\n            if nll < 0:\n                raise ValueError(\"neg_log_probs must be non-negative (did you forget the negation?)\")\n            if n < 0:\n                raise ValueError(\"token_counts must be non-negative\")\n            total_nll += float(nll)\n            total_tokens += int(n)\n        if total_tokens == 0:\n            return cls(perplexity=float(\"nan\"), avg_neg_log_likelihood=0.0, total_tokens=0)\n        avg_nll = total_nll / total_tokens\n        return cls(perplexity=math.exp(avg_nll), avg_neg_log_likelihood=avg_nll, total_tokens=total_tokens)\n\n\ndef perplexity(neg_log_probs: Sequence[float], token_counts: Sequence[int]) -> float:\n    return PerplexityResult.from_token_nll(neg_log_probs, token_counts).perplexity\n\n\ndef _validate_probs(confidences: np.ndarray, correct: np.ndarray) -> None:\n    if confidences.shape != correct.shape:\n        raise ValueError(\"confidences and correct must have the same shape\")\n    if confidences.ndim != 1:","sourceCodeStart":24,"sourceCodeEnd":60,"githubUrl":"https://github.com/rohitg00/ai-engineering-from-scratch/blob/39ea8a1c6d0b61f071226eff7ede4d4105fed820/phases/19-capstone-projects/73-perplexity-calibration/code/main.py#L24-L60","documentation":"from_token_nll accumulates negative log-likelihoods to compute exp(avg_nll); a negative entry usually means raw (positive) log-probabilities were passed instead of their negation, which would produce a perplexity below 1 — impossible for a language model — so the guard rejects it.","triggerScenarios":"Thrown at phases/19-capstone-projects/73-perplexity-calibration/code/main.py:42 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":["Negate log-probs before passing: neg_log_probs = [-p for p in log_probs]","If you already hold NLLs (e.g. from a loss), pass them directly without another negation","Add an assertion in your scoring loop that per-token NLL >= 0"],"exampleFix":null,"handlingStrategy":"validation","validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"39ea8a1c6d0b61f071226eff7ede4d4105fed820","analyzedAt":"2026-08-26T03:13:46.626Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}