• Updated:
  • Featured post

How LLMs generate the next token

(este post es una explicación de la teoría. dejo aquí otro post con el detalle práctico de como usar la temperature, top_k y top_p a efectos prácticos)

Explicación más en detalle de cómo obtienen los LLMs las probabilidades para generar el siguiente token

Sampling

En cada posición el modelo tiene una bolsa con miles de tokens posibles. Sampling es el proceso de no coger siempre el token más probable, si no de orientarlo a coger respuestas con determinadas características.

Si el modelo escogiera siempre el token con más probabilidades, obtendríamos respuestas aburridas y repetitivas.

Logits

Para generar el siguiente token, una red neuronal calcula primero los vectores de logits, donde cada logit corresponde a un valor posible. El tamaño de estos vectores de logits es tan grande como el vocabulario completo del modelo.

(representación de vectores de logits)

flowchart LR
	N1["What's your favorite color?"]:::note --> Z
	Z --> A1 --> A
	Z --> B1 --> B
	Z --> C1 --> C
	Z --> D1 --> D
	
	Z["Neural network"]
    A["a"]
    A1["(-0.5)"]
    B["green"]
    B1["(0.7)"]
    C["red"]
    C1["(0.5)"]
    D["the"]
    D1["(-1.2)"]
    
    classDef note fill:none,stroke:none,color:#777;    

Los logits NO representan probabilidades ya que no suman 1 y pueden incluso ser negativos (la probabilidades no pueden). Para convertir logits a probabilidades se usa una Softmax layer

Temperature

La temperatura es una constante que se aplica a los logits antes de la transformación de la Softmax layer. Se usa para ajustar la creatividad del modelo y redistribuir la probabilidad de los valores. Una temperatura más alta hace que el modelo sea más creativo ya que aumenta las posibilidades de elegir tokens menos probables.

xychart-beta
  title "Temperatura vs Probabilidad"
  x-axis "Temperatura (T)" [0.1, 0.2, 0.5, 1, 2, 5]
  y-axis "Probabilidad" 0 --> 1
  line "P(token1)" [0.9999546, 0.9933071, 0.8807971, 0.7310586, 0.6224593, 0.5498340]
  line "P(token2)" [0.0000454, 0.0066929, 0.1192029, 0.2689414, 0.3775407, 0.4501660]

Ejemplos de temperaturas:

  • Low (0.2-0.3): El modelo es cauto y elige las palabras más probables. Output factual y predecible.
  • Medium (0.5-0.7): Un mix de confiabilidad y engagement
  • High (0.9-1.0): Toma riesgos y es impredecible

Read More

Test APIs with Postman - Scripting

We can set pre-request scripts (run before the request) & tests (after execution) at several levels:

  • Collection
  • Folder
  • Request

Snippets

Inside pre-request Script and Tests we have a SNIPPETS column with templates we may use for our code.

Get / Set variables

console.log("Hello world");

// work with local vars
let urlVar = pm.variables.get("protocol");
console.log("value for protocol: " + urlVar);

pm.variables.set("protocol", "http");
console.log(pm.variables.get("protocol"));  

// work with global vars
let globalVar = pm.globals.get("env");
console.log(globalVar);

Read More

Test APIs with Postman - GUI

To test postman I use https://reqres.in. You can use it to learn how to write Postman tests.

Collections

Collections have metadata which you can set up. This includes:

  • Authorization so you don’t need to set it for every single request.
  • Variables, for variables only for this collection (so you don’t use environment vars).
  • Collection tests.

Read More

Error al crear imagenes en local (Minikube)

Hay un problema al intentar correr una imagen tuya propia en local con minikube. Minikube tiene su propio repositorio de imagenes y si no encuentra una imagen alli, la intenta descargar siempre del repositorio.

Solución

Set imagePullPolicy: IfNotPresent

Run the following command:

eval $(minikube docker-env)
# build again the image
# try to run it again

K8s config commands

Config

Azure

log-in into a tenant

az login --tenant 7f2c3a6b-e849-4d6f-b65d-1c0ef8b0f41c

configure local kubectl .kube config file

az aks get-credentials --resource-group my-aks --name aksname --admin

(the –admin part is optional but useful)

Contexts & Namespaces

see all configured contexts

kubectl config get-contexts

configure a context with a default namespace

kubectl config set-context <context_here> --namespace=<namespace_here>
# example
kubectl config set-context my-aks-context --namespace=aks-dev

Read More

Docker-compose how to export volumes to another machine

Data generated and used by Docker containers does not persist after restarts. We use Docker volumes to manage data to solve this issue. We use it to persist data in a container or share data between containers.

Volumes are the preferred mechanism for persisting data generated and user by Docker containers. Volumes are easier to back up or migrate.

Volumes are often a better choice than persisting data in a container’s writable layer, because a volume does not increase the size of the containers using it. The volume’s contents exist outside the lifecycle of a given container.

We have 3 volume types:

Anonymous volumes

Helpful to persist data temporarily. If we restart our container data is still visible. It doesn’t persist when we remove the container. Not accessible by other containers. They’re created inside /var/lib/docker/volume.

Example file:

version: '3.8'  
services:  
  db:  
    image: mysql  
    restart: always  
    environment:  
      MYSQL_ROOT_PASSWORD: root  
      MYSQL_DATABASE: test_db  
    ports:  
      - "3306:3306"  
    volumes:  
      - /var/lib/mysql

Read More

Migrate docker-compose to k8s

Steps to go from a docker-compose file, to build an Image out of the file, upload it to DockerHub, and run it with Kubernetes (minikube).

Set up

Install Kompose

# linux
curl -L https://github.com/kubernetes/kompose/releases/download/v1.22.0/kompose-linux-amd64 -o kompose
chmod +x kompose
sudo mv ./kompose /usr/local/bin/kompose

Clone App and Host It into DockerHub

Clone the files, go to the directory where your Dockerfile is and run:

# mariocodes is my DockerHub username
# kubernetes-custom-java-maven-app is the name of the repo I created at DockerHub
docker build -f Dockerfile -t mariocodes/kubernetes-custom-java-maven-app .

Read More

Common errors in k8s

STATUS CrashLoopBackOff

CrashLoopBackOff and no log appears. This happens as the container has no command to run so it start up and then immediately exits.

Give your image a command.

more here

apiVersion: v1
kind: Pod
metadata:
  name: twocontainers
spec:
  containers:
  - name: container1
    image: python:3.6-alpine
	command: ['sh', '-c', 'echo cont1 > index.html && python -m http.server 8082']
  - name: container2
    image: python:3.6-alpine
	command: ['sh', '-c', 'echo cont1 > index.html && python -m http.server 8083']

i18n & l10n

i18n is just a nomenclature for Internationalization. i18n involves, among other things, the ability to display translated content. It prepares a digital product for localization by for example, separate the content into strings so they are ready to be translated and delivered.

The same goes for L10n. This is a nomenclature for Localization. L10n involves translating content, adapting graphics and finalizing the producto for each regional market.

SQL Indexes

Indexes are a basic structure type that apply to one or multiple columns in order to improve performance and speed up queries that: filter, sort or join data for a table.

this may improve performance for a query that uses last_name in a WHERE clause or an ORDER BY

CREATE INDEX idx_last_name ON employees (last_name);

you can also create composite indexes

CREATE INDEX idx_composite ON employees (last_name, first_name)

and also composite index for only active employees

CREATE INDEX idx_active_employees ON employees (status) WHERE status = 'active';

When to use indexes

Frequent filters WHERE - if you usually filter by a specific column (last_name for example), an index should improve performance.

JOIN for big tables - when you use JOIN with big tables through PKs or FKs.

ORDER BY or GROUP BY - queries that search for / group by a specific column also benefit from indexes.

Best practices

Don’t create indexes in every column. This slows things down on insert, delete or update operations.

Index are best used for big domain fields such as ids, names, surnames. Don’t use them for male/female (or boolean) fields.

Keep indexes optimized: operations where you mass update or mass delete items in your tables may fragment your indexes. You may need to periodically check them and REINDEX them.

ALWAYS MEASURE PERFORMANCE TIME before and after the creation of that index. If your index doesn’t improve performance, remove it as it causes overhead.

Reference(s)

https://stackoverflow.com/questions/7744038/decision-when-to-create-index-on-table-column-in-database
https://stackoverflow.com/questions/52444912/how-to-find-out-fragmented-indexes-and-defragment-them-in-postgresql