from typing import List, Dict
import torch
from pandas import DataFrame
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import PreTrainedTokenizer
import pandas as pd
import numpy as np
from sklearn import preprocessing
def collate_batch(featurized_samples: List[Dict]):
input_ids = torch.nn.utils.rnn.pad_sequence(
[torch.tensor(x['input_ids']) for x in featurized_samples],
batch_first=True)
code
attention_masks = torch.nn.utils.rnn.pad_sequence(
[torch.tensor(x['attention_mask']) for x in featurized_samples],
batch_first=True)
batch = {"input_ids": input_ids,
"attention_masks": attention_masks,
"tokens": [x['tokens'] for x in featurized_samples],
"targets": np.array([x['target'] for x in featurized_samples]),
"ad_ids": [x['ad_id'] for x in featurized_samples]}
if 'token_type_ids' in featurized_samples[0]:
token_type_ids = torch.nn.utils.rnn.pad_sequence(
[torch.tensor(x['token_type_ids']) for x in featurized_samples],
batch_first=True)
batch["token_type_ids"] = token_type_ids
return batch
change this code to consider whole text which contains more than 512 tokens
To accommodate texts with more than 512 tokens, you'll need to make a few adjustments to the provided code. Here's how you can modify it to handle longer texts. We'll employ a strategy to truncate the text into chunks (if necessary) while still utilizing the maximum context that models like BERT, RoBERTa, etc., can handle (typically up to 512 tokens including special tokens). For texts exceeding this limit, we'll create overlapping chunks to ensure all content is processed.
Changes:
Text Chunking: Introduce a function to chunk long texts into manageable segments.
Overlap: Implement overlapping chunks to capture context across the chunk boundaries.
Modification to sample_to_features: Handle each chunk separately and store them appropriately.
Adjustments to DKZDataset and collate_batch: Accommodate the new chunked data structure.
Modified Code:
python
#!pip install torchtext==0.8.0 torch==1.7.1 pytorch-lightning==1.2.2
from typing import List, Dict
import torch
from pandas import DataFrame
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import PreTrainedTokenizer
import pandas as pd
import numpy as np
from sklearn import preprocessing
def chunk_text(input_text: str, tokenizer: PreTrainedTokenizer, max_length: int = 512, overlap: int = 128):
"""
Divide the input text into overlapping chunks to handle texts longer than the model's limit.
:param input_text: The text to be chunked.
:param tokenizer: The tokenizer used for encoding the text.
:param max_length: Maximum tokens per chunk (including special tokens like [CLS] and [SEP]).
:param overlap: Number of tokens to overlap between chunks for contextual continuity.
:return: A list of chunked tokenized inputs.
"""
encoding = tokenizer.encode_plus(input_text,
return_offsets_mapping=True,
max_length=max_length,
truncation=False,
return_tensors=None)
tokens = encoding['input_ids']
offset_mapping = encoding['offset_mapping']
chunks = []
start = 0
while start < len(tokens):
end = min(start + max_length - 2, len(tokens)) # Reserve space for CLS & SEP tokens
chunk_tokens = tokens[start:end]
# Adjust end to avoid splitting wordpiece tokens
if end < len(tokens) and offset_mapping[end][1] == offset_mapping[end-1][1]:
end -= 1
if end == start:
end += 1 # Ensure at least one token is included
# Re-encode the text span corresponding to the chunk tokens
chunk = tokenizer.encode_plus(
input_text[offset_mapping[start][0]:offset_mapping[end-1][1]],
padding='max_length',
max_length=max_length,
truncation=True,
return_tensors='pt'
)
chunks.append({
'input_ids': chunk['input_ids'].flatten(),
'attention_mask': chunk['attention_mask'].flatten(),
'tokens': chunk.encodings[0].tokens
})
# Move to the next chunk with overlap
start = end - overlap
return chunks
def sample_to_features(sample: pd.Series, tokenizer: PreTrainedTokenizer, label_column: str, max_length=512, overlap=128) -> Dict:
"""
Convert a sample into a featurized format with chunking.
:param sample: A pandas Series containing the text and label.
:param tokenizer: The tokenizer for encoding the text.
:param label_column: The column name of the label in the DataFrame.
:param max_length: Maximum length for each chunk.
:param overlap: Overlap size between chunks.
:return: A dictionary with chunked features and the original label.
"""
input_text = sample["description"]
chunks = chunk_text(input_text, tokenizer, max_length=max_length, overlap=overlap)
featurized_sample = {
"chunks": chunks,
"target": sample[label_column].astype(int),
"ad_id": sample["ad_id"]
}
return featurized_sample
def collate_batch(featurized_samples: List[Dict]):
"""
Collate a batch of chunked samples into tensors.
:param featurized_samples: A list of dictionaries, each containing chunked features and labels.
:return: A batch dictionary with padded tensors.
"""
# Flatten chunks across all samples into a single list
all_chunks = [chunk for sample in featurized_samples for chunk in sample['chunks']]
input_ids = torch.nn.utils.rnn.pad_sequence(
[torch.tensor(chunk['input_ids']) for chunk in all_chunks],
batch_first=True)
attention_masks = torch.nn.utils.rnn.pad_sequence(
[torch.tensor(chunk['attention_mask']) for chunk in all_chunks],
batch_first=True)
batch = {
"input_ids": input_ids,
"attention_masks": attention_masks,
"tokens": [chunk['tokens'] for chunk in all_chunks],
# Targets are repeated for each chunk of a sample
"targets": torch.tensor([sample['target'] for sample in featurized_samples for _ in sample['chunks']]),
"ad_ids": [f"{sample['ad_id']}_{i}" for sample in featurized_samples for i in range(len(sample['chunks']))]
}
if 'token_type_ids' in all_chunks[0]: # Assuming all chunks have the same structure
token_type_ids = torch.nn.utils.rnn.pad_sequence(
[torch.tensor(chunk['token_type_ids']) for chunk in all_chunks],
batch_first=True)
batch["token_type_ids"] = token_type_ids
return batch
class DKZDataset(Dataset):
def __init__(self,
file_path,
tokenizer: PreTrainedTokenizer,
max_length=512,
overlap=128):
"""
Initialize the dataset with chunking support.
:param file_path: Path to the dataset file.
:param tokenizer: Tokenizer for encoding texts.
:param max_length: Maximum tokens per chunk.
:param overlap: Overlap size between chunks.
"""
self.tokenizer: PreTrainedTokenizer = tokenizer
self.max_length = max_length
self.overlap = overlap
self.data: DataFrame = pd.read_parquet(file_path, engine="pyarrow")[:100].dropna()
label_encoder = preprocessing.LabelEncoder()
label_encoder.fit(self.data.dkz)
self.data.dkz = label_encoder.transform(self.data.dkz)
self.id2label = label_encoder.classes_
def __len__(self):
# Calculate the total number of chunks across all samples
return sum(len(sample_to_features(self.data.iloc[idx], self.tokenizer, "dkz", self.max_length, self.overlap)['chunks']) for idx in range(len(self.data)))
def __getitem__(self, index) -> T_co:
# Since __len__ now represents the total chunk count, we need to map this index back to a sample and then to its chunk
cumulative_chunks = [sum(len(sample_to_features(self.data.iloc[idx], self.tokenizer, "dkz", self.max_length, self.overlap)['chunks']) for idx in range(len(self.data))]
for i, cum_chunks in enumerate(cumulative_chunks):
if index < cum_chunks:
sample_idx = i
chunk_idx = index if i == 0 else index - cumulative_chunks[i-1]
break
featurized_sample = sample_to_features(self.data.iloc[sample_idx], self.tokenizer, "dkz", self.max_length, self.overlap)
return featurized_sample['chunks'][chunk_idx]
def get_num_classes(self):
return len(self.data["dkz"].unique())
Key Points:
Chunking Strategy: The chunk_text function splits the input text into overlapping chunks, ensuring that each chunk can be processed by the model.
Modified sample_to_features: Now returns a list of chunked features for each sample.
Adjusted collate_batch: Handles the flattened list of chunks from all samples, repeating targets for each chunk of a sample.
Updated DKZDataset: Reflects the change in __len__ to count chunks, not samples, and __getitem__ to map the chunk index back to a sample and its corresponding chunk.
Impact on Downstream Tasks:
Classification/Regression: When using chunking, the model processes each chunk separately. For classification or regression tasks, you can aggregate predictions from all chunks of a sample using techniques like voting, averaging, or concatenation followed by another layer. This ensures the model captures information from the entire text.
Overlap and Performance: Overlapping chunks help maintain contextual information across chunk boundaries, which can improve performance by reducing information loss. However, excessive overlap may introduce redundancy, affecting efficiency. A balance (e.g., 128-256 tokens overlap) typically works well, depending on the task and model.