Monday, 28 April 2025

How to control randomness and creativity of LLMs using Temperature parameter?

 

In the context of large language models (LLMs), temperature is a parameter used to control the randomness and creativity of the model's responses, especially when generating text.

 

What is Temperature?

Temperature is a value that influences the probabilities from which the model selects the next token (word or symbol) when generating text. It directly affects the distribution of probabilities for possible next tokens.

 

·       A low temperature (close to 0) makes the model more deterministic. It will tend to choose tokens with the highest probabilities (more predictable).

·       A high temperature (greater than 1) introduces more randomness into the process, allowing the model to consider less likely tokens as well, making the output more diverse or creative.

 

In short, temperature controls how "random the model is making its choices.

 

The Role of Temperature in Token Selection

When a language model generates text, it predicts the next token (word or character) based on the context of the preceding tokens. Each possible token has a probability assigned to it by the model. Temperature adjusts these probabilities in the following way.

 

Here's how a large language model (LLM) might finish the sentence "The dog is..." with different temperatures.

 

Low Temperature (0.1)

At a temperature of 0.1, the model will choose the most probable continuation, producing a very predictable and straightforward response. The output is likely to be consistent and boring, as the model is focusing on the most likely options.

·       "The dog is barking."

·       "The dog is cute."

·       "The dog is friendly."

 

These completions are simple, safe, and highly probable based on common associations with dogs.

 

High Temperature (1.5 or 2)

At a higher temperature (1.5 or 2), the model is more likely to choose less probable words, allowing for more variety and creative responses. The output may seem unusual, funny, or unexpected.

·       "The dog is wearing sunglasses and dancing."

·       "The dog is trying to solve a Rubik's cube."

·       "The dog is a secret agent on a mission."

·       "The dog is floating in space with a helmet on."

 

These completions are more playful, creative, and unpredictable, reflecting the added randomness of the higher temperature.

 

Why is Temperature Important?

·       Creativity vs. Consistency: Temperature lets you control the balance between creativity and consistency. A higher temperature might produce more unexpected or imaginative responses, while a lower temperature keeps the response more consistent with the given input.

·       Use Cases: In tasks like creative writing or brainstorming, a higher temperature is often desirable because it gives novel ideas. For more structured tasks, like generating code or answering factual questions, a lower temperature is preferred for accurate and reliable output.

 

What are the maximum and minimum values of the temperature?

In most language models, the temperature parameter typically has a range of values that is not strictly bound to a specific minimum or maximum. Most Of the LLMs are using in the range between 0 and 2. Refer below articles for more details.

 

https://community.openai.com/t/does-temperature-go-to-1-or-2/174095/5

 

https://platform.openai.com/docs/api-reference/audio#chat-create-temperature

 

https://platform.openai.com/docs/api-reference/audio

 

 

In summary,

·       Low Temperature (0.1): Produces straightforward, typical responses based on the most likely continuation.

·       High Temperature (1.5 or 2): Produces varied, sometimes nonsensical, or more creative responses.

 

References

https://ivibudh.medium.com/a-guide-to-controlling-llm-model-output-exploring-top-k-top-p-and-temperature-parameters-ed6a31313910

Previous                                                    Next                                                    Home

How Randomness in Language Models Powers Creativity and Engaging Responses?

When we interact with language models like GPT (Generative Pretrained Transformer), it might feel like we’re chatting with something that’s truly creative. You might notice that the model doesn’t always provide the same response to the same question. Sometimes it gives you a creative answer, and other times it feels more formal or structured. This behavior is powered by a concept known as randomness in the token generation process, which is key to making the model’s output more interesting and varied.

 

Read my previous post, before reading this topic (How LLM generate next token from given input tokens?).

 

1. What is a Token in Language Models?

A token is essentially a piece of a word, a word itself, or sometimes even punctuation. When a language model generates text, it generates one token at a time. At each step, the model predicts the next token based on the context of the conversation or the input it's given.

 

For example, if you type "I love", the model might predict that the next word could be "coding", "dogs", "food", or many other possibilities, depending on what it has learned.

 

2. How Does the Model Pick the Next Token?

When the model predicts the next token, it does so by calculating the likelihood of various possible tokens using a probability distribution. This distribution is based on the patterns the model learned during training, where it saw millions of examples of how language works.

 

Let’s say the model has a 60% probability of choosing "dogs" and a 40% probability of choosing "cats", 35% of probability choosing cooking as the next token after "I love". Based purely on these probabilities, "dogs" would be the most likely choice, but there's still a chance the model could pick "cats".

 

3. Why Doesn’t the Model Always Pick the Most Likely Token?

Now here’s where the fun part comes in. To make the conversation feel more natural, dynamic, and sometimes even creative, the model doesn't always pick the token with the highest probability. Instead, it introduces randomness into its decision-making.

 

This is a way of simulating creativity. Just like when humans have different ideas or express themselves in various ways, the model can mix up its responses by occasionally picking less likely tokens. This randomness is controlled through parameters like temperature and sampling techniques.

4. Temperature: Adding Creativity to the Response

One of the main ways randomness is introduced is through a setting called temperature. Temperature controls how "risky" or "creative" the model’s responses are:

 

  • Low temperature (close to 0): The model is more likely to choose the token with the highest probability. The result is more predictable and structured, but less creative.
  • High temperature (greater than 1): The model’s choice is more random, allowing for more varied and sometimes surprising answers. This can make the model sound more creative and less repetitive.

 

For example, if you ask the model, "What’s a good dinner idea?", at a low temperature, you might get something like "Spaghetti with tomato sauce." But at a high temperature, you could get more varied responses, like "Grilled salmon with roasted vegetables" or "Sushi with miso soup" — both reasonable and creative ideas.

 

5. Top-k Sampling: Ensuring a Balanced Output

Another technique used to introduce randomness is top-k sampling. In this approach, instead of considering every possible token the model could generate, it limits the selection to only the top "k" most likely tokens. This balances between randomness and quality, ensuring that the response is both creative and sensible.

 

For example, if the model is deciding the next word, it might only consider the top 5 words with the highest probabilities, rather than every word in its vocabulary. The model then randomly selects one from these top 5 options.

 

6. How Does This Make the Model More Creative?

By introducing these techniques, the model doesn’t just spit out the most likely or boring responses. Instead, it can generate text that feels dynamic and more like a human conversation. For instance, when asked a question, the model might provide answers that are surprising or creative.

 

This degree of unpredictability allows the model to generate creative ideas, jokes, analogies, and even poetry! It helps the model feel less like a machine that just repeats the same thing and more like a "creative" entity that can come up with different responses to the same question.

 

7. Why Does This Make the Model Engaging?

One of the key reasons people find generative AI engaging is its ability to keep the conversation fresh and unpredictable. If the model always gave the same response, it would feel more like a scripted chatbot. But by mixing things up with randomness, it feels like you're having a more lively, natural interaction.

 

For example, in a storytelling scenario, a model might offer several different endings to a story, each equally valid but completely different. This makes the conversation engaging, as you never know exactly what to expect.

 

In summary, The LLM model doesn't always select the token with the highest probability from the distribution. Instead, a certain level of randomness is introduced to mimic creative thinking. As a result, the model doesn't generate the exact same output for identical inputs each time. This gives users the impression that Generative AI is creative and engaging.

Previous                                                    Next                                                    Home

Javalin: Get all the form parameters mapped to a name

Context#formParams("name") method return the list of form parameters by name.

Example 

List<String> myHobbies = ctx.formParams("hobbies");

 Find the below working application.

Step 1: Create new maven project ‘javalin-list-form-params-by-name’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>javalin-list-form-params-by-name</artifactId>
	<version>1.0.0</version>

	<properties>
		<packaging>jar</packaging>
		<jdk.version>17</jdk.version>
		<release.version>17</release.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>io.javalin</groupId>
			<artifactId>javalin</artifactId>
			<version>5.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>2.0.3</version>
		</dependency>


		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.14.0</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.14.0</version>
		</dependency>


	</dependencies>

	<build>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.10.1</version>
				<configuration>
					<source>17</source>
					<target>17</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
				</configuration>
				<executions>
					<execution>
						<id>assemble-all</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

 

Step 3: Define JsonUtil class.

 

JsonUtil.java

 

package com.sample.app.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	public static String marshal(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}

	public static <T> T unmarshal(Class<T> clazz, String json)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		return (T) mapper.readValue(json, clazz);
	}
}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sample.app.util.JsonUtil;

import io.javalin.Javalin;
import io.javalin.http.HttpStatus;

public class App {

	public static void main(String[] args) {

		Javalin javalin = Javalin.create();

		javalin.get("/", (ctx) -> {
			ctx.result("Welcome to Javalin programming!!!!");
		});

		javalin.post("/form-params-demo", (ctx) -> {
			List<String> myHobbies = ctx.formParams("hobbies");

			Map<String, Object> receivedData = new HashMap<>();
			receivedData.put("hobbies", myHobbies);

			ctx.result(JsonUtil.marshal(receivedData)).status(HttpStatus.CREATED);
		});

		javalin.start(8080);
	}

}

Total project structure looks like below.



Build the project

Navigate to the folder, where pom.xml is located and execute the command ‘mvn package’.

 

Upon successful command execution, you can see a ‘javalin-list-form-params-by-name-1.0.0-jar-with-dependencies.jar’ file.

 

$ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
javalin-list-form-params-by-name-1.0.0-jar-with-dependencies.jar
javalin-list-form-params-by-name-1.0.0.jar
maven-archiver
maven-status
test-classes

Run the application

Execute below command to run the application.

java -jar ./target/javalin-list-form-params-by-name-1.0.0-jar-with-dependencies.jar

$java -jar ./target/javalin-list-form-params-by-name-1.0.0-jar-with-dependencies.jar
[main] INFO io.javalin.Javalin - Starting Javalin ...
[main] INFO org.eclipse.jetty.server.Server - jetty-11.0.13; built: 2022-12-07T20:47:15.149Z; git: a04bd1ccf844cf9bebc12129335d7493111cbff6; jvm 17.0.5+9-LTS-191
[main] INFO org.eclipse.jetty.server.session.DefaultSessionIdManager - Session workerName=node0
[main] INFO org.eclipse.jetty.server.handler.ContextHandler - Started i.j.j.@30ee2816{/,null,AVAILABLE}
[main] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@26a7b76d{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
[main] INFO org.eclipse.jetty.server.Server - Started Server@1fc2b765{STARTING}[11.0.13,sto=0] @385ms
[main] INFO io.javalin.Javalin - 
       __                  ___          ______
      / /___ __   ______ _/ (_)___     / ____/
 __  / / __ `/ | / / __ `/ / / __ \   /___ \
/ /_/ / /_/ /| |/ / /_/ / / / / / /  ____/ /
\____/\__,_/ |___/\__,_/_/_/_/ /_/  /_____/

       https://javalin.io/documentation

[main] INFO io.javalin.Javalin - Listening on http://localhost:8080/
[main] INFO io.javalin.Javalin - You are running Javalin 5.3.2 (released January 22, 2023).
[main] INFO io.javalin.Javalin - Javalin started in 265ms \o/

Test the api

Execute below curl command.

curl --location --request POST 'http://localhost:8080/form-params-demo' \
--form 'hobbies="chess"' \
--form 'hobbies="cricket"'

$curl --location --request POST 'http://localhost:8080/form-params-demo' \
> --form 'hobbies="chess"' \
> --form 'hobbies="cricket"'
{"hobbies":["chess","cricket"]}

 

You can download this application from this link.

Previous                                                    Next                                                    Home

Javalin: validate form parameters

Using Context.formParamAsClass("name", clazz), we can validate the form parameter.

Example 

String name = ctx.formParamAsClass("name", String.class).getOrDefault("no_name");

 

Find the below working application.

 

Step 1: Create new maven project ‘javalin-validate-form-parameter’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>javalin-validate-form-parameter</artifactId>
	<version>1.0.0</version>

	<properties>
		<packaging>jar</packaging>
		<jdk.version>17</jdk.version>
		<release.version>17</release.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>io.javalin</groupId>
			<artifactId>javalin</artifactId>
			<version>5.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>2.0.3</version>
		</dependency>


		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.14.0</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.14.0</version>
		</dependency>


	</dependencies>

	<build>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.10.1</version>
				<configuration>
					<source>17</source>
					<target>17</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
				</configuration>
				<executions>
					<execution>
						<id>assemble-all</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

Step 3: Define JsonUtil class.

 

JsinUtil.java

package com.sample.app.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	public static String marshal(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}

	public static <T> T unmarshal(Class<T> clazz, String json)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		return (T) mapper.readValue(json, clazz);
	}
}

 

Step 4: Define App class.

 

App.java

 

package com.sample.app;

import java.util.HashMap;
import java.util.Map;

import com.sample.app.util.JsonUtil;

import io.javalin.Javalin;
import io.javalin.http.HttpStatus;

public class App {

	public static void main(String[] args) {

		Javalin javalin = Javalin.create();

		javalin.get("/", (ctx) -> {
			ctx.result("Welcome to Javalin programming!!!!");
		});

		javalin.post("/form-params-demo", (ctx) -> {

			String name = ctx.formParamAsClass("name", String.class)
					.getOrDefault("no_name");
			
			String age = ctx.formParamAsClass("age", String.class)
					.getOrDefault("no_age");

			Map<String, Object> receivedData = new HashMap<>();
			receivedData.put("name", name);
			receivedData.put("age", age);

			ctx.result(JsonUtil.marshal(receivedData)).status(HttpStatus.CREATED);
		});

		javalin.start(8080);
	}

}

 Total project structure looks like below.

 


Build the project

Navigate to the folder, where pom.xml is located and execute the command ‘mvn package’.

 

Upon successful command execution, you can see a ‘javalin-validate-form-parameter-1.0.0-jar-with-dependencies.jar’ file.

$ls ./target 
archive-tmp
classes
generated-sources
generated-test-sources
javalin-validate-form-parameter-1.0.0-jar-with-dependencies.jar
javalin-validate-form-parameter-1.0.0.jar
maven-archiver
maven-status
test-classes

 

Run the application

Execute below command to run the application.

$java -jar ./target/javalin-validate-form-parameter-1.0.0-jar-with-dependencies.jar
[main] INFO io.javalin.Javalin - Starting Javalin ...
[main] INFO org.eclipse.jetty.server.Server - jetty-11.0.13; built: 2022-12-07T20:47:15.149Z; git: a04bd1ccf844cf9bebc12129335d7493111cbff6; jvm 17.0.5+9-LTS-191
[main] INFO org.eclipse.jetty.server.session.DefaultSessionIdManager - Session workerName=node0
[main] INFO org.eclipse.jetty.server.handler.ContextHandler - Started i.j.j.@30ee2816{/,null,AVAILABLE}
[main] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@26a7b76d{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
[main] INFO org.eclipse.jetty.server.Server - Started Server@1fc2b765{STARTING}[11.0.13,sto=0] @410ms
[main] INFO io.javalin.Javalin - 
       __                  ___          ______
      / /___ __   ______ _/ (_)___     / ____/
 __  / / __ `/ | / / __ `/ / / __ \   /___ \
/ /_/ / /_/ /| |/ / /_/ / / / / / /  ____/ /
\____/\__,_/ |___/\__,_/_/_/_/ /_/  /_____/

       https://javalin.io/documentation

[main] INFO io.javalin.Javalin - Listening on http://localhost:8080/
[main] INFO io.javalin.Javalin - You are running Javalin 5.3.2 (released January 22, 2023).
[main] INFO io.javalin.Javalin - Javalin started in 283ms \o/

Test the api

Example 1: Do not pass name and age

curl --location --request POST 'http://localhost:8080/form-params-demo'

$curl --location --request POST 'http://localhost:8080/form-params-demo'
{"name":"no_name","age":"no_age"}

 

Example 2: Pass name but not age.

curl --location --request POST 'http://localhost:8080/form-params-demo' \
--form 'name="krishna"'

$curl --location --request POST 'http://localhost:8080/form-params-demo' \
> --form 'name="krishna"'
{"name":"krishna","age":"no_age"}

 

Example 3: Pass both name and age.

curl --location --request POST 'http://localhost:8080/form-params-demo' \
--form 'name="krishna"' \
--form 'age="18"'

$curl --location --request POST 'http://localhost:8080/form-params-demo' \
> --form 'name="krishna"' \
> --form 'age="18"'
{"name":"krishna","age":"18"}

You can download this application from this link.

 

Previous                                                    Next                                                    Home