Path: blob/master/Generative NLP Models using Python/6 Transformers for NLP.ipynb
3074 views
Transformers" in the context of artificial intelligence are a type of computer model designed to understand and generate human language. They're really good at tasks like translating languages, answering questions, and generating text.
Transformers rely on a mechanism called "self-attention" to weigh the importance of different words in a sentence when processing language data. This mechanism allows them to capture long-range dependencies and relationships between words more effectively than previous models. As a result, Transformers have achieved state-of-the-art performance in many NLP tasks, including language translation, text summarization, question answering, and sentiment analysis.
Self-attention is a technique used in NLP that helps models to understand relationships between words or entities in a sentence, no matter where they appear. It is a important part of transformers model which is used in tasks like translation and text generation.
Understanding Attention in NLP
The goal of self attention mechanism is to improve performance of traditional models such as encoder-decoder models used in RNNs (Recurrent Neural Networks).
In traditional encoder-decoder models input sequence is compressed into a single fixed-length vector which is then used to generate the output.
This works well for short sequences but struggles with long ones because important information can be lost when compressed into a single vector.
Self-Attention Mechanism Explained
The self-attention mechanism is a key innovation behind models like Transformers (e.g., BERT, GPT). It allows models to weigh the importance of different words in a sequence relative to each other.
1. What is Self-Attention?
Self-Attention lets a model attend to all positions of a sequence to compute a representation of that sequence.
It’s used to model dependencies between tokens, even if they are far apart.
It allows a model to dynamically focus on relevant parts of the input for each token.
2. Core Idea
Given an input sequence of token embeddings:
[ X = [x_1, x_2, ..., x_n] ]
We transform these into Query (Q), Key (K), and Value (V) vectors:
[ Q = XW^Q,\quad K = XW^K,\quad V = XW^V ]
Where (W^Q, W^K, W^V) are learnable weight matrices.
3. Scaled Dot-Product Attention
For each token:
Compute attention scores using dot product between its Query and all Keys: [ \text{AttentionScore}(i,j) = Q_i \cdot K_j^T ]
Scale the scores: [ \text{ScaledScore} = \frac{QK^T}{\sqrt{d_k}} ]
Apply softmax to get attention weights: [ \text{AttentionWeights} = \text{softmax}\left( \frac{QK^T}{\sqrt{d_k}} \right) ]
Multiply by Values: [ \text{Output} = \text{AttentionWeights} \cdot V ]
4. Multi-Head Attention
Instead of performing a single attention function, we run multiple in parallel (called "heads"):
[ \text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, ..., \text{head}_h)W^O ]
Each head learns different representations, helping the model attend to information from different subspaces.
5. Role in Transformers
Self-Attention is used in Encoder and Decoder blocks.
Captures contextual information for each token efficiently.
Enables parallelization (vs. RNNs).
Key Advantages
Long-range dependency modeling
Parallel computation
Dynamic contextualization of words
Scales better than recurrent models
. Summary
Component | Role |
---|---|
Query (Q) | Current word's focus |
Key (K) | Candidate words to attend to |
Value (V) | Contains information to combine |
Softmax | Normalizes attention scores |
Multi-head | Allows model to attend to different perspectives |
The key components of Transformer models include:
Self-Attention Mechanism: This is the core component of Transformers. Self-attention allows the model to weigh the importance of different words in a sentence when processing language data. It enables capturing contextual relationships between words in a sequence, facilitating better understanding of the input.
Multi-Head Attention: In Transformers, self-attention is typically used in multiple "heads" or parallel attention mechanisms. Each head allows the model to focus on different parts of the input, enabling it to capture different types of relationships simultaneously.
Positional Encoding: Since Transformer models do not inherently understand the sequential order of input tokens like recurrent neural networks (RNNs), positional encoding is added to the input embeddings to provide information about the position of each token in the sequence.
Feedforward Neural Networks: Transformers include feedforward neural networks as part of their architecture. These networks are applied independently to each token's representation after self-attention and positional encoding, allowing the model to capture non-linear relationships between features.
Encoder and Decoder Layers: Transformer architectures often consist of encoder and decoder layers. The encoder processes the input sequence, while the decoder generates the output sequence in tasks like sequence-to-sequence translation. Each layer in the encoder and decoder typically includes self-attention and feedforward neural network sub-layers.
Residual Connections and Layer Normalization: To facilitate training deep networks, Transformers use residual connections around each sub-layer followed by layer normalization. These techniques help alleviate the vanishing gradient problem and improve the flow of information through the network.
Masking: In tasks like language translation, where the entire input sequence is available during training, masking is applied to prevent the model from attending to future tokens when predicting the output sequence.
These components work together to enable Transformers to achieve state-of-the-art performance in various natural language processing tasks.
Word Embedding
Word embedding is a technique used to represent words as vectors (arrays of numbers). These vectors capture semantic relationships between words.
let's implement a basic position encoding scheme to add positional information to the word embeddings:
Positional encoding is a crucial concept in the Transformer architecture, enabling the model to capture the order of words in a sequence since Transformers lack inherent sequential information. Let's break down the concept using a simple example with the sentence "suyashi is happy".
Understanding Positional Encoding In a Transformer model, each word is embedded into a high-dimensional space using an embedding matrix. However, the position of each word in the sequence is not captured by these embeddings. Positional encoding addresses this by adding a unique positional information to each word embedding.
Positional Encoding Formula The most common method for positional encoding in Transformers involves using sine and cosine functions of different frequencies. For a position 𝑝 𝑜 𝑠 pos and a dimension 𝑖 i of the encoding, the positional encoding is defined as:
3. Example: "suyashi is happy"
Let's consider a simple example where we encode a small part of the sequence using positional encoding. Assume the sentence "suyashi is happy" has four positions (0, 1, 2, 3), and we use a small dimension d=4 for simplicity.
Resulting Positional Encodings
Combining these, we get the positional encodings for each position
If the word embeddings for "suyashi", "is", "happy" are vectors, the positional encoding vectors would be added to these embeddings. This addition ensures that the model is aware of the position of each word in the sentence.
In practice, these operations are done over higher-dimensional spaces and with many more positions, but the fundamental idea remains the same. The positional encodings help the Transformer model understand the order and position of words within a sequence
We define the position encoding function and word embeddings as we did previously.
We concatenate word embeddings with position encodings to create input vectors.
The self_attention function calculates attention scores using dot product and scales them by the square root of the dimensionality of the embeddings.
Softmax is applied to obtain attention weights.
The attention weights are then used to compute the attended inputs by applying them to the input vectors.
Finally, we display the attended inputs and attention weights.
Simplified implementation using NumPy to demonstrate self-attention
steps:
X represents the input token embeddings.
W_q, W_k, and W_v represent the query, key, and value projection matrices respectively.
We compute the dot products of query and key matrices to get the attention scores.
Softmax is applied to the attention scores to get the attention weights.
Finally, we compute the weighted sum of value vectors to get the output.
Simplified Python code demonstrating how self-attention might be applied in a neural machine translation scenario using the transformers library
This code uses the BERT model from the transformers library to tokenize the input text, compute its hidden states, and extract the self-attention weights. These weights indicate how much each token attends to every other token in each layer of the model. However, note that BERT is not specifically trained for machine translation, so this is just an illustration of self-attention in a language model context.
Steps
Tokenization: The input text "Ashi is beautiful." is tokenized into its constituent tokens using the BERT tokenizer. Each token is represented by an integer ID. Let's denote the tokenized input as 𝑋 X.
Model Computation: The tokenized input 𝑋
X is fed into the BERT model, which consists of multiple layers of self-attention and feedforward neural networks. The BERT model processes the input tokens and produces hidden states for each token. Let's denote the hidden states as 𝐻
Self-Attention: During each layer of the BERT model, self-attention is applied to the input tokens. The self-attention mechanism computes attention scores between each token and every other token in the sequence. These attention scores are calculated using the formula:
Self-Attention Weights: The self-attention weights represent the importance of each token attending to every other token in the sequence. These weights are computed for each layer of the model. In the code, the mean of the attention weights across the sequence dimension is calculated for each layer and printed out.
Example Language Translation
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[15], line 7
5 model_name = 'Helsinki-NLP/opus-mt-en-hi'
6 tokenizer = MarianTokenizer.from_pretrained(model_name)
----> 7 hindi_tran = MarianMTModel.from_pretrained(model_name)
9 # Input text
10 input_text = input("Enter text for transalation = ")
, in restore_default_torch_dtype.<locals>._wrapper(*args, **kwargs)
307 old_dtype = torch.get_default_dtype()
308 try:
--> 309 return func(*args, **kwargs)
310 finally:
311 torch.set_default_dtype(old_dtype)
, in PreTrainedModel.from_pretrained(cls, pretrained_model_name_or_path, config, cache_dir, ignore_mismatched_sizes, force_download, local_files_only, token, revision, use_safetensors, weights_only, *model_args, **kwargs)
4563 if dtype_orig is not None:
4564 torch.set_default_dtype(dtype_orig)
4566 (
4567 model,
4568 missing_keys,
4569 unexpected_keys,
4570 mismatched_keys,
4571 offload_index,
4572 error_msgs,
-> 4573 ) = cls._load_pretrained_model(
4574 model,
4575 state_dict,
4576 checkpoint_files,
4577 pretrained_model_name_or_path,
4578 ignore_mismatched_sizes=ignore_mismatched_sizes,
4579 sharded_metadata=sharded_metadata,
4580 device_map=device_map,
4581 disk_offload_folder=offload_folder,
4582 offload_state_dict=offload_state_dict,
4583 dtype=torch_dtype,
4584 hf_quantizer=hf_quantizer,
4585 keep_in_fp32_regex=keep_in_fp32_regex,
4586 device_mesh=device_mesh,
4587 key_mapping=key_mapping,
4588 weights_only=weights_only,
4589 )
4591 # record tp degree the model sharded to
4592 model._tp_size = tp_size
, in PreTrainedModel._load_pretrained_model(cls, model, state_dict, checkpoint_files, pretrained_model_name_or_path, ignore_mismatched_sizes, sharded_metadata, device_map, disk_offload_folder, offload_state_dict, dtype, hf_quantizer, keep_in_fp32_regex, device_mesh, key_mapping, weights_only)
4829 original_checkpoint_keys = list(state_dict.keys())
4830 else:
4831 original_checkpoint_keys = list(
-> 4832 load_state_dict(checkpoint_files[0], map_location="meta", weights_only=weights_only).keys()
4833 )
4835 # Check if we are in a special state, i.e. loading from a state dict coming from a different architecture
4836 prefix = model.base_model_prefix
, in load_state_dict(checkpoint_file, is_quantized, map_location, weights_only)
551 # Fallback to torch.load (if weights_only was explicitly False, do not check safety as this is known to be unsafe)
552 if weights_only:
--> 553 check_torch_load_is_safe()
554 try:
555 if map_location is None:
, in check_torch_load_is_safe()
1415 def check_torch_load_is_safe():
1416 if not is_torch_greater_or_equal("2.6"):
-> 1417 raise ValueError(
1418 "Due to a serious vulnerability issue in `torch.load`, even with `weights_only=True`, we now require users "
1419 "to upgrade torch to at least v2.6 in order to use the function. This version restriction does not apply "
1420 "when loading files with safetensors."
1421 "\nSee the vulnerability report here https://nvd.nist.gov/vuln/detail/CVE-2025-32434"
1422 )
ValueError: Due to a serious vulnerability issue in `torch.load`, even with `weights_only=True`, we now require users to upgrade torch to at least v2.6 in order to use the function. This version restriction does not apply when loading files with safetensors.
See the vulnerability report here https://nvd.nist.gov/vuln/detail/CVE-2025-32434
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[16], line 6
4 model_name = "Helsinki-NLP/opus-mt-en-de"
5 tokenizer = MarianTokenizer.from_pretrained(model_name)
----> 6 model = MarianMTModel.from_pretrained(model_name)
8 # Input text in English
9 input_text = input("Enter the Text: ")
, in restore_default_torch_dtype.<locals>._wrapper(*args, **kwargs)
307 old_dtype = torch.get_default_dtype()
308 try:
--> 309 return func(*args, **kwargs)
310 finally:
311 torch.set_default_dtype(old_dtype)
, in PreTrainedModel.from_pretrained(cls, pretrained_model_name_or_path, config, cache_dir, ignore_mismatched_sizes, force_download, local_files_only, token, revision, use_safetensors, weights_only, *model_args, **kwargs)
4563 if dtype_orig is not None:
4564 torch.set_default_dtype(dtype_orig)
4566 (
4567 model,
4568 missing_keys,
4569 unexpected_keys,
4570 mismatched_keys,
4571 offload_index,
4572 error_msgs,
-> 4573 ) = cls._load_pretrained_model(
4574 model,
4575 state_dict,
4576 checkpoint_files,
4577 pretrained_model_name_or_path,
4578 ignore_mismatched_sizes=ignore_mismatched_sizes,
4579 sharded_metadata=sharded_metadata,
4580 device_map=device_map,
4581 disk_offload_folder=offload_folder,
4582 offload_state_dict=offload_state_dict,
4583 dtype=torch_dtype,
4584 hf_quantizer=hf_quantizer,
4585 keep_in_fp32_regex=keep_in_fp32_regex,
4586 device_mesh=device_mesh,
4587 key_mapping=key_mapping,
4588 weights_only=weights_only,
4589 )
4591 # record tp degree the model sharded to
4592 model._tp_size = tp_size
, in PreTrainedModel._load_pretrained_model(cls, model, state_dict, checkpoint_files, pretrained_model_name_or_path, ignore_mismatched_sizes, sharded_metadata, device_map, disk_offload_folder, offload_state_dict, dtype, hf_quantizer, keep_in_fp32_regex, device_mesh, key_mapping, weights_only)
4829 original_checkpoint_keys = list(state_dict.keys())
4830 else:
4831 original_checkpoint_keys = list(
-> 4832 load_state_dict(checkpoint_files[0], map_location="meta", weights_only=weights_only).keys()
4833 )
4835 # Check if we are in a special state, i.e. loading from a state dict coming from a different architecture
4836 prefix = model.base_model_prefix
, in load_state_dict(checkpoint_file, is_quantized, map_location, weights_only)
551 # Fallback to torch.load (if weights_only was explicitly False, do not check safety as this is known to be unsafe)
552 if weights_only:
--> 553 check_torch_load_is_safe()
554 try:
555 if map_location is None:
, in check_torch_load_is_safe()
1415 def check_torch_load_is_safe():
1416 if not is_torch_greater_or_equal("2.6"):
-> 1417 raise ValueError(
1418 "Due to a serious vulnerability issue in `torch.load`, even with `weights_only=True`, we now require users "
1419 "to upgrade torch to at least v2.6 in order to use the function. This version restriction does not apply "
1420 "when loading files with safetensors."
1421 "\nSee the vulnerability report here https://nvd.nist.gov/vuln/detail/CVE-2025-32434"
1422 )
ValueError: Due to a serious vulnerability issue in `torch.load`, even with `weights_only=True`, we now require users to upgrade torch to at least v2.6 in order to use the function. This version restriction does not apply when loading files with safetensors.
See the vulnerability report here https://nvd.nist.gov/vuln/detail/CVE-2025-32434
pip install wordcloud --trusted-host pypi.org --trusted-host files.pythonhosted.org pip install pipeline
Hindi to Tamil
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[17], line 6
4 # Define the model and tokenizer for English to Hindi
5 model_name_en_to_hi = 'Helsinki-NLP/opus-mt-en-hi'
----> 6 model_en_to_hi = MarianMTModel.from_pretrained(model_name_en_to_hi)
7 tokenizer_en_to_hi = MarianTokenizer.from_pretrained(model_name_en_to_hi)
9 def translate_en_to_hi(text):
, in restore_default_torch_dtype.<locals>._wrapper(*args, **kwargs)
307 old_dtype = torch.get_default_dtype()
308 try:
--> 309 return func(*args, **kwargs)
310 finally:
311 torch.set_default_dtype(old_dtype)
, in PreTrainedModel.from_pretrained(cls, pretrained_model_name_or_path, config, cache_dir, ignore_mismatched_sizes, force_download, local_files_only, token, revision, use_safetensors, weights_only, *model_args, **kwargs)
4563 if dtype_orig is not None:
4564 torch.set_default_dtype(dtype_orig)
4566 (
4567 model,
4568 missing_keys,
4569 unexpected_keys,
4570 mismatched_keys,
4571 offload_index,
4572 error_msgs,
-> 4573 ) = cls._load_pretrained_model(
4574 model,
4575 state_dict,
4576 checkpoint_files,
4577 pretrained_model_name_or_path,
4578 ignore_mismatched_sizes=ignore_mismatched_sizes,
4579 sharded_metadata=sharded_metadata,
4580 device_map=device_map,
4581 disk_offload_folder=offload_folder,
4582 offload_state_dict=offload_state_dict,
4583 dtype=torch_dtype,
4584 hf_quantizer=hf_quantizer,
4585 keep_in_fp32_regex=keep_in_fp32_regex,
4586 device_mesh=device_mesh,
4587 key_mapping=key_mapping,
4588 weights_only=weights_only,
4589 )
4591 # record tp degree the model sharded to
4592 model._tp_size = tp_size
, in PreTrainedModel._load_pretrained_model(cls, model, state_dict, checkpoint_files, pretrained_model_name_or_path, ignore_mismatched_sizes, sharded_metadata, device_map, disk_offload_folder, offload_state_dict, dtype, hf_quantizer, keep_in_fp32_regex, device_mesh, key_mapping, weights_only)
4829 original_checkpoint_keys = list(state_dict.keys())
4830 else:
4831 original_checkpoint_keys = list(
-> 4832 load_state_dict(checkpoint_files[0], map_location="meta", weights_only=weights_only).keys()
4833 )
4835 # Check if we are in a special state, i.e. loading from a state dict coming from a different architecture
4836 prefix = model.base_model_prefix
, in load_state_dict(checkpoint_file, is_quantized, map_location, weights_only)
551 # Fallback to torch.load (if weights_only was explicitly False, do not check safety as this is known to be unsafe)
552 if weights_only:
--> 553 check_torch_load_is_safe()
554 try:
555 if map_location is None:
, in check_torch_load_is_safe()
1415 def check_torch_load_is_safe():
1416 if not is_torch_greater_or_equal("2.6"):
-> 1417 raise ValueError(
1418 "Due to a serious vulnerability issue in `torch.load`, even with `weights_only=True`, we now require users "
1419 "to upgrade torch to at least v2.6 in order to use the function. This version restriction does not apply "
1420 "when loading files with safetensors."
1421 "\nSee the vulnerability report here https://nvd.nist.gov/vuln/detail/CVE-2025-32434"
1422 )
ValueError: Due to a serious vulnerability issue in `torch.load`, even with `weights_only=True`, we now require users to upgrade torch to at least v2.6 in order to use the function. This version restriction does not apply when loading files with safetensors.
See the vulnerability report here https://nvd.nist.gov/vuln/detail/CVE-2025-32434
import sys print("Python version:", sys.version)
Sentiment Analysis
We are using distilbert-base-uncased-finetuned-sst-2-english model, which is fine-tuned for sentiment analysis on the Stanford Sentiment Treebank (SST-2) dataset.