Implementation:AI4Finance Foundation FinGPT tokenize
| Knowledge Sources | |
|---|---|
| Domains | NLP, Data_Preprocessing |
| Last Updated | 2026-10-18 00:00 GMT |
Overview
Concrete tool for tokenizing instruction-response pairs for supervised fine-tuning provided by the FinGPT Benchmark and Forecaster utilities.
Description
The tokenize function converts instruction-input-output examples into tokenized `input_ids` and `labels` for training. It constructs a prompt via `get_prompt`, tokenizes the prompt and target separately, concatenates them, adds an EOS token, and masks the prompt portion in the labels (set to `pad_token_id`) so the model only learns to generate the response.
The Benchmark version (in `FinGPT_Benchmark/utils.py`) uses `tokenizer()` with padding=False, while the Forecaster version (in `FinGPT_Forecaster/utils.py`) uses `tokenizer.encode()`. Both produce the same output structure: `input_ids`, `labels`, and `exceed_max_length` flag.
Usage
Import this function when you need to prepare tokenized datasets for training:
- Benchmark training: Tokenizing instruction-tuning examples with configurable templates.
- Forecaster training: Tokenizing prompt-answer pairs for LoRA fine-tuning.
- Dataset.map: Used with `partial(tokenize, args, tokenizer)` for batch tokenization.
Code Reference
Source Location
- Repository: FinGPT
- File: fingpt/FinGPT_Benchmark/utils.py (L77-131), fingpt/FinGPT_Forecaster/utils.py (L19-44)
Signature
# Benchmark version
def tokenize(
args: Namespace,
tokenizer: AutoTokenizer,
feature: dict,
) -> dict
# Forecaster version (same signature, uses tokenizer.encode)
def tokenize(
args: Namespace,
tokenizer: AutoTokenizer,
feature: dict,
) -> dict
Import
from utils import tokenize # Benchmark
from utils import tokenize # Forecaster
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| args | Namespace | Yes | Contains max_length and instruct_template |
| tokenizer | AutoTokenizer | Yes | HuggingFace tokenizer |
| feature | dict | Yes | Dict with 'instruction', 'input', 'output' (Benchmark) or 'prompt', 'answer' (Forecaster) |
Outputs
| Name | Type | Description |
|---|---|---|
| input_ids | list[int] | Concatenated prompt + target token IDs + EOS |
| labels | list[int] | pad_token_id for prompt, target IDs for response |
| exceed_max_length | bool | True if combined length >= args.max_length |
Usage Examples
Tokenize with Dataset.map
from functools import partial
from utils import tokenize
# Tokenize entire dataset
dataset = dataset.map(partial(tokenize, args, tokenizer))
# Filter out examples exceeding max length
dataset = dataset.filter(lambda x: not x['exceed_max_length'])
# Remove original columns
dataset = dataset.remove_columns(['instruction', 'input', 'output', 'exceed_max_length'])