Model Fluency Comparison in Language Models
Introduction to Model Fluency
Welcome to the final lesson of the "Scoring LLM Outputs with Logprobs and Perplexity" course. In previous lessons, you explored how to extract log probabilities and calculate perplexity to evaluate language models. Building on that foundation, this lesson will focus on comparing the fluency of different language models, using perplexity as a measure of how confident each model is in the text it generates. By the end of this lesson, you will be able to compare models using the perplexity of their own answers, and you will know what such a comparison can and cannot tell you.
Setting Up the Environment
Before we dive into the code, let's ensure your environment is ready. If you're working on your local machine, you'll need to install the openai library. You can do this using pip:
The math library is part of Python's standard library, so no installation is needed for it. However, if you're using the CodeSignal environment, these libraries are already pre-installed, allowing you to focus on the code without worrying about setup.
Understanding the Code Structure
Let's break down the code snippet you'll be working with. It compares how confident different language models are in the answers they generate, using log probabilities. We start by importing the necessary libraries: math for mathematical operations and OpenAI for sending requests to the models. Next, we initialize the client, define a list of models and a prompt, and process the prompt for each model individually. Each request specifies the model, the message content, and parameters such as max_tokens and logprobs, which control how many tokens are generated and whether log probabilities are returned. Finally, we average the log probabilities of all generated tokens and convert the average into a perplexity.
Example: Comparing Perplexity Across Models
A note on models and providers: the models used in this example are set up for you on CodeSignal. If you run similar code on your own machine, check your provider's documentation first: model names, API keys and supported parameters differ between providers and models. In particular, not every model returns log probabilities, which is why the code checks that they are present.
Now, let's see the code in action with a practical example. We send the prompt "Explain how photosynthesis works." to two models. We allow up to 400 tokens, because some newer models need extra room before they finish an answer.
Comparing model confidence on: "Explain how photosynthesis works."
deepseek-ai/DeepSeek-V3: Tokens scored: 394 Average Log Probability: -0.2407 Perplexity: 1.27
deepseek-ai/DeepSeek-V4-Flash: Tokens scored: 279 Average Log Probability: -0.0843 Perplexity: 1.09
