Codificación posicional para representar el orden
Incorpore la posición de la secuencia en los tokens
Codificación posicional para representar el orden es una lección gratuita de Deep Learning Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Deep Learning Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Deep Learning Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Attention Ignores Order
Self-attention treats a sentence like a bag of tokens. Shuffle the words and the math barely changes, so the model has no built-in sense of order.
Order Carries Meaning
But order matters: "dog bites man" is not "man bites dog". We must hand the model some signal about each token's position.
Add, Do Not Append
The trick is to add a position vector directly to each token's embedding. Same shape, so attention sees content and place fused together.
x = token_emb + pos_embSinusoidal Encoding
The original transformer used fixed sine and cosine waves of different frequencies, one pattern per dimension, to mark each position.
Why Sine Waves
Mixing frequencies gives every position a unique fingerprint, and the smooth waves let the model generalize to lengths it never saw in training.
The Formula
Even dimensions use sine, odd dimensions use cosine, with the wavelength growing across dimensions. That is the whole encoding recipe.
pe[:, 0::2] = torch.sin(pos / div)
pe[:, 1::2] = torch.cos(pos / div)Relative Distance
A neat bonus: with sinusoids, the offset between two positions is easy to express, helping attention reason about relative distance.
Learned Positions
Modern models often skip sinusoids and use a learned embedding table, one trainable vector per position, just like word embeddings.
self.pos_emb = nn.Embedding(max_len, d_model)Fixed vs Learned
Fixed sinusoids extrapolate to new lengths for free; learned tables fit your data but are capped at the maximum length you trained on.
Rotary Encoding
Newer transformers favor rotary position encoding, which rotates query and key vectors by an angle tied to position, baking order into attention itself.
Where It Goes
Whatever scheme you pick, positional info is injected once at the input, before the first attention layer ever runs.
Quick Check
Let's check why positional encoding exists.
Recap
You learned that attention ignores order, so we add positional encodings, whether sinusoidal, learned, or rotary, to tell tokens where they sit. Well done!
Preguntas frecuentes
¿La lección «Codificación posicional para representar el orden» es gratis?
Sí — el texto completo de «Codificación posicional para representar el orden» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Deep Learning Academy, actualiza a CoddyKit PRO. El curso de Deep Learning Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Codificación posicional para representar el orden»?
Incorpore la posición de la secuencia en los tokens Practicas Deep Learning Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Deep Learning Academy?
No se requiere experiencia previa. Deep Learning Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Codificación posicional para representar el orden»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Deep Learning Academy?
Sí. Cada lección de Deep Learning Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Self-attention: query, key y value
- Producto punto escalado y multi-head
- Codificación posicional para representar el orden
- Apile un bloque de encoder Transformer