Training API¶
This page documents the model training components of AniSearch Model.
Overview¶
The training package provides functionality for fine-tuning cross-encoder models on anime and manga data. It includes:
- Base trainer class with common functionality
- Specialized trainers for anime and manga
- Dataset handling utilities
- Training utilities
Data Processing Flow¶
The following diagram illustrates how data flows through the training process:
flowchart LR
A[(Raw Dataset)] --> B[Load Dataset]
B --> C[Filter Light Novels]
C --> D[Clean Data]
D --> E[Generate Training Pairs]
E --> F[Create Query Variations]
F --> G[Create Positive/Negative Examples]
G --> H[Prepare Model Input]
H --> I[Fine-tune Model]
subgraph Manga Specific
C
end
subgraph Both Trainers
D
E
F
G
H
I
end
style A fill:#e3f2fd,stroke:#1976d2
style I fill:#e8f5e9,stroke:#4caf50
Similarity Score Calculation¶
When generating synthetic training data, the system calculates similarity scores between entries based on their metadata:
flowchart TD
A[Start] --> B[Parse Genre Lists]
B --> C[Parse Theme Lists]
C --> D{Both Lists Empty?}
D -->|Yes| E[Return 0.0]
D -->|No| F[Calculate Jaccard Similarity]
F --> G[Weight Themes Higher]
G --> H[Cap Score at 0.8]
H --> I[Return Final Score]
style A fill:#e3f2fd,stroke:#1976d2
style E fill:#ffebee,stroke:#f44336
style I fill:#e8f5e9,stroke:#4caf50
This process ensures that synthetic training pairs reflect meaningful relationships between entries based on their genres and themes.
Base Trainer¶
The foundation class with core training functionality:
src.training.base_trainer.BaseModelTrainer ¶
BaseModelTrainer(dataset_type: str = 'anime', model_name: str = MODEL_NAME, epochs: int = DEFAULT_EPOCHS, batch_size: int = DEFAULT_BATCH_SIZE, eval_steps: int = DEFAULT_EVAL_STEPS, warmup_steps: int = DEFAULT_WARMUP_STEPS, max_samples: int = DEFAULT_MAX_SAMPLES, learning_rate: float = DEFAULT_LEARNING_RATE, eval_split: float = 0.1, seed: int = 42, device: Optional[str] = None, dataset_path: Optional[str] = None)
Base trainer class for fine-tuning cross-encoder models on anime/manga datasets.
This class provides the core functionality for training cross-encoder models on anime and manga datasets. It handles dataset preparation, synthetic training data generation, model configuration, and training execution. The trainer supports various training parameters and loss functions, allowing for flexible model tuning.
The trainer creates training examples by pairing titles (queries) with synopses (documents), generating both positive pairs (matching title-synopsis) and negative pairs (title with unrelated synopsis). It can also generate variations of queries to improve model robustness.
ATTRIBUTE | DESCRIPTION |
---|---|
dataset_type | Type of dataset ('anime' or 'manga') TYPE: |
model_name | Name or path of the base model to fine-tune TYPE: |
epochs | Number of training epochs TYPE: |
batch_size | Training batch size TYPE: |
eval_steps | Number of steps between evaluations TYPE: |
warmup_steps | Number of warmup steps for learning rate scheduler TYPE: |
max_samples | Maximum number of training samples to use TYPE: |
learning_rate | Learning rate for the optimizer TYPE: |
eval_split | Fraction of data to use for evaluation TYPE: |
seed | Random seed for reproducibility TYPE: |
device | Device to use for training ('cpu', 'cuda', etc.) TYPE: |
dataset_path | Path to the dataset file TYPE: |
df | The loaded dataset TYPE: |
output_path | Path where the fine-tuned model will be saved TYPE: |
synopsis_cols | Columns containing synopsis information TYPE: |
id_col | Column containing the ID for anime/manga entries TYPE: |
Example
# Initialize a trainer for anime dataset
trainer = BaseModelTrainer(
dataset_type="anime",
model_name="cross-encoder/ms-marco-MiniLM-L-6-v2",
epochs=3,
batch_size=16
)
# Train the model
output_path = trainer.train(loss_type="mse")
# Create labeled data for inspection
trainer.create_and_save_labeled_data(
output_file="labeled_anime_data.csv",
n_samples=5000
)
Notes
- The trainer requires merged datasets to be available. If not found, it will suggest running the merge_datasets.py script first.
- For best results, ensure the dataset contains adequate synopsis information and relevant metadata like genres and themes.
- The trainer automatically handles text truncation to fit within model token limits, prioritizing the query (title) over the document (synopsis).
This constructor sets up the training environment, loads the appropriate dataset, and prepares internal state for the training process. It validates inputs, sets up random seeds for reproducibility, configures the device, and establishes the model output path.
PARAMETER | DESCRIPTION |
---|---|
dataset_type | The type of dataset to use for training. Must be either 'anime' or 'manga'. This determines which dataset is loaded and how certain processing steps are performed. Default is 'anime'. TYPE: |
model_name | The name or path of the base cross-encoder model to fine-tune. Can be a HuggingFace model identifier or a local path. Default is the value from MODEL_NAME constant. TYPE: |
epochs | Number of complete passes through the training dataset. Higher values may improve performance but risk overfitting. Default is DEFAULT_EPOCHS (3). TYPE: |
batch_size | Number of examples processed in each training step. Larger batches provide more stable gradients but require more memory. Default is DEFAULT_BATCH_SIZE (16). TYPE: |
eval_steps | Number of training steps between model evaluations. If not specified, a reasonable value will be calculated based on dataset size. Default is DEFAULT_EVAL_STEPS (500). TYPE: |
warmup_steps | Number of steps for learning rate warm-up. During warm-up, the learning rate gradually increases from 0 to the specified rate. Default is DEFAULT_WARMUP_STEPS (500). TYPE: |
max_samples | Maximum number of training samples to use from the dataset. Useful for limiting training time or for testing. Set to None to use all available data. Default is DEFAULT_MAX_SAMPLES (10000). TYPE: |
learning_rate | Learning rate for the optimizer. Controls how quickly model weights are updated during training. Default is DEFAULT_LEARNING_RATE (2e-6). TYPE: |
eval_split | Fraction of data to use for evaluation instead of training. Must be between 0 and 1. Default is 0.1 (10% for evaluation). TYPE: |
seed | Random seed for reproducibility. Ensures the same training/evaluation split and data sampling across runs. Default is 42. TYPE: |
device | Device to use for training ('cpu', 'cuda', 'cuda:0', etc.). If None, automatically selects GPU if available, otherwise CPU. Default is None. TYPE: |
dataset_path | Path to the dataset file. If None, uses the default path based on dataset_type. Default is None. TYPE: |
RAISES | DESCRIPTION |
---|---|
ValueError | If dataset_type is not 'anime' or 'manga' |
FileNotFoundError | If the dataset file doesn't exist |
Notes
- The method automatically creates the output directory if it doesn't exist
- The output path is constructed from the model name and dataset type
- After initialization, the dataset is prepared by calling _prepare_dataset()
Source code in src/training/base_trainer.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
|
dataset_path instance-attribute
¶
dataset_path = ANIME_DATASET_PATH if dataset_type == 'anime' else MANGA_DATASET_PATH
output_path instance-attribute
¶
output_path = join(MODEL_SAVE_PATH, f'{model_basename}-{dataset_type}-finetuned')
warmup_steps_specified instance-attribute
¶
warmup_steps_specified = warmup_steps != DEFAULT_WARMUP_STEPS
create_and_save_labeled_data ¶
create_and_save_labeled_data(output_file: str, n_samples: int = 10000, include_partial_matches: bool = True) -> None
Create and save synthetic labeled data to a CSV file for inspection or custom training.
This method generates a rich dataset of labeled examples with various levels of relevance between queries and documents. Unlike the synthetic training data used directly for training (which uses binary labels), this method creates examples with graded relevance scores between 0.0 and 1.0, capturing partial matches based on content similarity.
The generated CSV file includes:
- Perfect matches: Title paired with its own synopsis (score 1.0)
- Partial matches: Title paired with synopses of similar content based on genres and themes (scores 0.1-0.8)
- Query variations: Conversational variations of titles (e.g., "Looking for X") paired with matching synopses (score 1.0)
PARAMETER | DESCRIPTION |
---|---|
output_file | Path to save the labeled data CSV file. If the directory doesn't exist, it will be created. If writing fails due to permissions, the file will be saved to the current directory. TYPE: |
n_samples | Number of base entries to sample from the dataset for creating labeled examples. The actual number of examples in the output will be larger due to variations and partial matches. Default is 10000. TYPE: |
include_partial_matches | Whether to include examples with partial relevance based on genre/theme similarity. When True, the dataset will include examples with scores between 0.1 and 0.8. When False, only perfect matches (1.0) and variations will be included. Default is True. TYPE: |
RETURNS | DESCRIPTION |
---|---|
None | The method saves the labeled data to a file but doesn't return a value. TYPE: |
Example
# Create labeled data with default settings
trainer = BaseModelTrainer(dataset_type="anime")
trainer.create_and_save_labeled_data("data/labeled_anime.csv")
# Create a smaller dataset without partial matches
trainer.create_and_save_labeled_data(
"data/simple_labeled_anime.csv",
n_samples=5000,
include_partial_matches=False
)
Notes
- The output CSV includes an 'example_type' column indicating the type of each example (positive, variation_positive, or similarity-based)
- Similarity-based scores are rounded to the nearest 0.1 for cleaner values
- Query variations are added to approximately 50% of the titles
- The method handles permission errors by falling back to the current directory
- The method logs a distribution of scores in the final dataset
Source code in src/training/base_trainer.py
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 |
|
create_query_variations ¶
Create natural language variations of base queries to enhance training robustness.
This method generates conversational and alternative phrasings of the base queries to help the model recognize the same intent expressed in different ways. For each base query, it creates variations using templates like "I'm looking for {query}" or "Find me {query}".
Query variations are important for training more robust models that can handle real-world search inputs, which often contain conversational phrases and different formulations of the same information need.
PARAMETER | DESCRIPTION |
---|---|
base_queries | List of original query strings (typically anime/manga titles) that will be used as the basis for generating variations. TYPE: |
n_variations | Number of variations to create for each base query. The actual number may be less if there aren't enough templates. Default is 7. TYPE: |
RETURNS | DESCRIPTION |
---|---|
List[str] | List[str]: A combined list containing both the original queries and their variations. The length will be approximately len(base_queries) * (1 + n_variations), but may be less if n_variations exceeds the number of available templates. |
Example
# Create variations of anime titles
titles = ["Naruto", "One Piece", "Attack on Titan"]
trainer = BaseModelTrainer(dataset_type="anime")
variations = trainer.create_query_variations(titles, n_variations=3)
# Print all variations
for var in variations:
print(var)
# Example output:
# Naruto
# I'm looking for Naruto
# Can you recommend Naruto?
# Find me Naruto
# One Piece
# ...etc.
Notes
- The method always includes the original queries in the returned list
- Templates are selected randomly for each query
- The method is designed for English language variations
- The method is decorated with handle_exceptions for error handling
Source code in src/training/base_trainer.py
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 |
|
create_synthetic_training_data ¶
Create synthetic training data pairs for cross-encoder model fine-tuning.
This method generates a balanced dataset of positive and negative examples:
- Positive examples: Pairs of titles with their matching synopses (label 1.0)
- Negative examples: Pairs of titles with randomly selected unrelated synopses (label 0.0)
For each positive example, the method creates 3 negative examples, resulting in a 1:3 ratio of positive to negative examples. This ratio helps the model learn to distinguish relevant from irrelevant content.
The method samples up to max_samples entries from the dataset and applies randomization with the configured seed for reproducibility. Examples with empty titles or synopses are skipped.
RETURNS | DESCRIPTION |
---|---|
List[InputExample] | List[InputExample]: A list of InputExample objects ready for training, where each example contains: - texts[0]: A title (query) - texts[1]: A synopsis (document) - label: 1.0 for positive pairs, 0.0 for negative pairs |
Example
# Create synthetic training data
trainer = BaseModelTrainer(dataset_type="anime")
examples = trainer.create_synthetic_training_data()
# Examine the first few examples
for i, example in enumerate(examples[:5]):
print(f"Example {i}:")
print(f" Query: {example.texts[0][:50]}...")
print(f" Document: {example.texts[1][:50]}...")
print(f" Label: {example.label}")
Notes
- The method is decorated with handle_exceptions for error handling
- Results are shuffled before returning to randomize the training order
- If max_samples is smaller than the dataset size, a random subset is used
- The 1:3 positive-to-negative ratio is a common practice in information retrieval tasks to handle the natural imbalance of relevant vs. irrelevant documents
Source code in src/training/base_trainer.py
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 |
|
create_training_data_from_labeled_file ¶
Create training data from a pre-labeled CSV file instead of synthetic generation.
This method allows for using custom or human-labeled data for training. The labeled file should be a CSV containing at least three columns:
- query: The search query or title
- text: The document or synopsis text
- score: A numerical score/label (typically 0-1) indicating relevance
Using labeled data gives more control over the training examples and can incorporate domain expertise about what constitutes good matches. It's especially useful for fine-grained relevance levels beyond just binary classification.
PARAMETER | DESCRIPTION |
---|---|
labeled_file | Path to the CSV file containing labeled examples. The file must include 'query', 'text', and 'score' columns. TYPE: |
RETURNS | DESCRIPTION |
---|---|
List[InputExample] | List[InputExample]: A list of InputExample objects created from the labeled file, where each example contains: - texts[0]: The query from the 'query' column - texts[1]: The document from the 'text' column - label: The float score from the 'score' column |
RAISES | DESCRIPTION |
---|---|
FileNotFoundError | If the labeled_file doesn't exist |
ValueError | If the required columns are missing from the file |
Example
# Create training data from labeled file
trainer = BaseModelTrainer(dataset_type="anime")
examples = trainer.create_training_data_from_labeled_file(
"path/to/labeled_data.csv"
)
# Print distribution of scores
score_counts = {}
for example in examples:
score = example.label
score_counts[score] = score_counts.get(score, 0) + 1
for score, count in sorted(score_counts.items()):
print(f"Score {score}: {count} examples")
Notes
- The method is decorated with handle_exceptions for error handling
- No shuffling is performed as the labeled file may already have a specific order
- Empty values in the CSV are converted to empty strings
- The scores are converted to float values
Source code in src/training/base_trainer.py
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
|
train ¶
Train the cross-encoder model with the prepared dataset.
This method executes the full training pipeline:
- Prepares training data (synthetic or from labeled file)
- Splits data into training and evaluation sets
- Truncates text pairs to fit model token limits
- Configures the model, loss function, and training arguments
- Executes the training process
- Saves the fine-tuned model
The method supports various loss functions and learning rate schedulers to optimize different aspects of model performance. It automatically handles device placement, batching, and evaluation during training.
PARAMETER | DESCRIPTION |
---|---|
labeled_file | Optional path to a pre-labeled CSV file containing training examples. If provided, uses this file instead of generating synthetic data. Default is None (generate synthetic data). TYPE: |
loss_type | Type of loss function to use for training. Supported options: - 'mse' (default): Mean Squared Error loss - 'binary_cross_entropy': Binary Cross Entropy loss - 'cross_entropy': Cross Entropy loss - 'lambda': LambdaLoss for LambdaRank-style learning to rank - 'list_mle', 'p_list_mle': ListMLE/PListMLE losses for listwise learning - 'list_net': ListNet loss for listwise learning - 'multiple_negatives_ranking': Multiple Negatives Ranking loss - 'cached_multiple_negatives_ranking': Cached version of MNR loss - 'margin_mse': Margin MSE loss - 'rank_net': RankNet loss for pairwise learning TYPE: |
scheduler | Learning rate scheduler type. Options include: - 'linear' (default): Linear decay from initial value to 0 - 'cosine': Cosine decay schedule - 'cosine_with_restarts': Cosine decay with periodic restarts - 'polynomial': Polynomial decay - 'constant': Constant learning rate - 'constant_with_warmup': Constant learning rate after warmup TYPE: |
RETURNS | DESCRIPTION |
---|---|
str | Path to the saved fine-tuned model, which can be loaded later for inference or additional training. TYPE: |
Example
# Train a model with default settings
trainer = BaseModelTrainer(
dataset_type="anime",
model_name="cross-encoder/ms-marco-MiniLM-L-6-v2",
epochs=3
)
model_path = trainer.train()
print(f"Model saved to: {model_path}")
# Train with custom loss and scheduler
trainer2 = BaseModelTrainer(dataset_type="manga")
model_path = trainer2.train(
loss_type="binary_cross_entropy",
scheduler="cosine"
)
Notes
- The method automatically calculates reasonable evaluation and warmup steps if they weren't explicitly specified during initialization
- Training progress is logged using tqdm progress bars and the logger
- The model with the best evaluation performance is automatically saved
- The method is decorated with handle_exceptions for error handling
Source code in src/training/base_trainer.py
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 |
|
Anime Trainer¶
Specialized trainer for anime models:
src.training.anime_trainer.AnimeModelTrainer ¶
AnimeModelTrainer(model_name: str = MODEL_NAME, epochs: int = DEFAULT_EPOCHS, batch_size: int = DEFAULT_BATCH_SIZE, eval_steps: int = DEFAULT_EVAL_STEPS, warmup_steps: int = DEFAULT_WARMUP_STEPS, max_samples: int = DEFAULT_MAX_SAMPLES, learning_rate: float = DEFAULT_LEARNING_RATE, eval_split: float = 0.1, seed: int = 42, device: Optional[str] = None, dataset_path: Optional[str] = None)
Bases: BaseModelTrainer
Specialized trainer for fine-tuning cross-encoder models on anime datasets.
This class extends the BaseModelTrainer with anime-specific functionality, simplifying the creation of search models optimized for anime content. It automatically configures the training process for anime datasets and provides anime-specific query generation for more robust training.
The trainer creates relevant training examples using anime titles and synopses, and generates query variations that reflect how users typically search for anime content (e.g., "Looking for anime about...", "Anime similar to...").
ATTRIBUTE | DESCRIPTION |
---|---|
dataset_type | Fixed to "anime" to specify this trainer works with anime datasets. TYPE: |
model_name | Name of the base cross-encoder model used for fine-tuning. TYPE: |
epochs | Number of training epochs. TYPE: |
batch_size | Number of examples processed in each training step. TYPE: |
eval_steps | Number of steps between model evaluations. TYPE: |
warmup_steps | Number of warmup steps for the learning rate scheduler. TYPE: |
max_samples | Maximum number of training samples to use. TYPE: |
learning_rate | Learning rate for the optimizer. TYPE: |
eval_split | Fraction of data used for evaluation. TYPE: |
seed | Random seed for reproducibility. TYPE: |
device | Device used for training (cpu or cuda). TYPE: |
df | The loaded anime dataset after preparation. TYPE: |
Example
# Initialize a trainer for anime model
trainer = AnimeModelTrainer(
model_name="cross-encoder/ms-marco-MiniLM-L-6-v2",
epochs=5,
batch_size=16
)
# Train the model with MSE loss and linear scheduler
model_path = trainer.train(loss_type="mse", scheduler="linear")
print(f"Anime search model saved to: {model_path}")
# Create labeled data for inspection
trainer.create_and_save_labeled_data(
output_file="anime_labeled_data.csv",
n_samples=5000
)
Notes
- The trainer automatically uses the default anime dataset path unless specified
- For best results, ensure your anime dataset contains adequate synopsis information and metadata like genres and themes
- This class sets dataset_type="anime" in the parent class, focusing all operations on anime data
This constructor sets up the training environment specifically for anime data, passing "anime" as the dataset_type to the parent class. It configures all training parameters and loads the appropriate anime dataset.
PARAMETER | DESCRIPTION |
---|---|
model_name | The name or path of the base cross-encoder model to fine-tune. Can be a HuggingFace model identifier or a local path. Default is the value from MODEL_NAME constant. TYPE: |
epochs | Number of complete passes through the training dataset. Higher values may improve performance but risk overfitting. Default is DEFAULT_EPOCHS (3). TYPE: |
batch_size | Number of examples processed in each training step. Larger batches provide more stable gradients but require more memory. Default is DEFAULT_BATCH_SIZE (16). TYPE: |
eval_steps | Number of training steps between model evaluations. If not specified, a reasonable value will be calculated based on dataset size. Default is DEFAULT_EVAL_STEPS (500). TYPE: |
warmup_steps | Number of steps for learning rate warm-up. During warm-up, the learning rate gradually increases from 0 to the specified rate. Default is DEFAULT_WARMUP_STEPS (500). TYPE: |
max_samples | Maximum number of training samples to use from the anime dataset. Useful for limiting training time or for testing. Set to None to use all available data. Default is DEFAULT_MAX_SAMPLES (10000). TYPE: |
learning_rate | Learning rate for the optimizer. Controls how quickly model weights are updated during training. Default is DEFAULT_LEARNING_RATE (2e-6). TYPE: |
eval_split | Fraction of data to use for evaluation instead of training. Must be between 0 and 1. Default is 0.1 (10% for evaluation). TYPE: |
seed | Random seed for reproducibility. Ensures the same training/evaluation split and data sampling across runs. Default is 42. TYPE: |
device | Device to use for training ('cpu', 'cuda', 'cuda:0', etc.). If None, automatically selects GPU if available, otherwise CPU. Default is None. TYPE: |
dataset_path | Path to the anime dataset file. If None, uses the default anime dataset path. Default is None. TYPE: |
Notes
- This constructor passes "anime" as the dataset_type to the parent class
- The method automatically creates the output directory if it doesn't exist
- The output path is constructed from the model name and "anime"
- After initialization, the anime dataset is prepared for training
Source code in src/training/anime_trainer.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
|
create_query_variations ¶
Create anime-specific variations of base queries to improve training robustness.
This method overrides the parent class implementation to generate query variations specifically tailored for anime search, using templates that reflect how users typically search for anime content (e.g., "Looking for anime about...", "Anime similar to...").
The variations help the model learn to recognize the same anime-related intent expressed in different ways, making it more robust to real-world search queries.
PARAMETER | DESCRIPTION |
---|---|
base_queries | List of original query strings (typically anime titles or descriptions) that will be used as the basis for generating variations. TYPE: |
n_variations | Number of anime-specific variations to create for each base query. If this exceeds the number of available templates, all templates will be used. Default is 7. TYPE: |
RETURNS | DESCRIPTION |
---|---|
List[str] | List[str]: A combined list containing both the original queries and their anime-specific variations. The length will be approximately len(base_queries) * (1 + n_variations), but may be less if n_variations exceeds the number of available templates. |
Example
# Create variations of anime titles
titles = ["Naruto", "One Piece", "Attack on Titan"]
trainer = AnimeModelTrainer()
variations = trainer.create_query_variations(titles, n_variations=3)
# Print all variations
for var in variations:
print(var)
# Example output:
# Naruto
# Looking for anime about Naruto
# I want to watch anime with Naruto
# Find me anime where Naruto
# One Piece
# ...etc.
Notes
- The method always includes the original queries in the returned list
- Templates are selected randomly for each query
- All templates include the word "anime" to help the model recognize anime-specific search patterns
- This anime-specific implementation provides better training examples than the generic implementation in the parent class
Source code in src/training/anime_trainer.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 |
|
Manga Trainer¶
Specialized trainer for manga models:
src.training.manga_trainer.MangaModelTrainer ¶
MangaModelTrainer(model_name: str = MODEL_NAME, epochs: int = DEFAULT_EPOCHS, batch_size: int = DEFAULT_BATCH_SIZE, eval_steps: int = DEFAULT_EVAL_STEPS, warmup_steps: int = DEFAULT_WARMUP_STEPS, max_samples: int = DEFAULT_MAX_SAMPLES, learning_rate: float = DEFAULT_LEARNING_RATE, eval_split: float = 0.1, seed: int = 42, device: Optional[str] = None, dataset_path: Optional[str] = None, include_light_novels: bool = False)
Bases: BaseModelTrainer
Specialized trainer for fine-tuning cross-encoder models on manga datasets.
This class extends the BaseModelTrainer with manga-specific functionality, simplifying the creation of search models optimized for manga content. It automatically configures the training process for manga datasets and provides manga-specific query generation for more robust training.
The trainer creates relevant training examples using manga titles and synopses, and generates query variations that reflect how users typically search for manga content (e.g., "Looking for manga about...", "Manga similar to...").
ATTRIBUTE | DESCRIPTION |
---|---|
dataset_type | Fixed to "manga" to specify this trainer works with manga datasets. TYPE: |
include_light_novels | Flag indicating whether light novels should be included in the training dataset. When False, light novels are filtered out. TYPE: |
model_name | Name of the base cross-encoder model used for fine-tuning. TYPE: |
epochs | Number of training epochs. TYPE: |
batch_size | Number of examples processed in each training step. TYPE: |
eval_steps | Number of steps between model evaluations. TYPE: |
warmup_steps | Number of warmup steps for the learning rate scheduler. TYPE: |
max_samples | Maximum number of training samples to use. TYPE: |
learning_rate | Learning rate for the optimizer. TYPE: |
eval_split | Fraction of data used for evaluation. TYPE: |
seed | Random seed for reproducibility. TYPE: |
device | Device used for training (cpu or cuda). TYPE: |
df | The loaded manga dataset after preparation. TYPE: |
Example
# Initialize a trainer for manga model, excluding light novels
trainer = MangaModelTrainer(
model_name="cross-encoder/ms-marco-MiniLM-L-6-v2",
epochs=5,
batch_size=16,
include_light_novels=False
)
# Train the model with MSE loss and linear scheduler
model_path = trainer.train(loss_type="mse", scheduler="linear")
print(f"Manga search model saved to: {model_path}")
# Create labeled data for inspection
trainer.create_and_save_labeled_data(
output_file="manga_labeled_data.csv",
n_samples=5000
)
Notes
- The trainer automatically uses the default manga dataset path unless specified
- For best results, ensure your manga dataset contains adequate synopsis information and metadata like genres and themes
- This class sets dataset_type="manga" in the parent class, focusing all operations on manga data
- Light novels can be excluded from training to create more manga-specific models
This constructor sets up the training environment specifically for manga data, passing "manga" as the dataset_type to the parent class. It configures all training parameters, loads the appropriate manga dataset, and optionally filters out light novels from the dataset.
PARAMETER | DESCRIPTION |
---|---|
model_name | The name or path of the base cross-encoder model to fine-tune. Can be a HuggingFace model identifier or a local path. Default is the value from MODEL_NAME constant. TYPE: |
epochs | Number of complete passes through the training dataset. Higher values may improve performance but risk overfitting. Default is DEFAULT_EPOCHS (3). TYPE: |
batch_size | Number of examples processed in each training step. Larger batches provide more stable gradients but require more memory. Default is DEFAULT_BATCH_SIZE (16). TYPE: |
eval_steps | Number of training steps between model evaluations. If not specified, a reasonable value will be calculated based on dataset size. Default is DEFAULT_EVAL_STEPS (500). TYPE: |
warmup_steps | Number of steps for learning rate warm-up. During warm-up, the learning rate gradually increases from 0 to the specified rate. Default is DEFAULT_WARMUP_STEPS (500). TYPE: |
max_samples | Maximum number of training samples to use from the manga dataset. Useful for limiting training time or for testing. Set to None to use all available data. Default is DEFAULT_MAX_SAMPLES (10000). TYPE: |
learning_rate | Learning rate for the optimizer. Controls how quickly model weights are updated during training. Default is DEFAULT_LEARNING_RATE (2e-6). TYPE: |
eval_split | Fraction of data to use for evaluation instead of training. Must be between 0 and 1. Default is 0.1 (10% for evaluation). TYPE: |
seed | Random seed for reproducibility. Ensures the same training/evaluation split and data sampling across runs. Default is 42. TYPE: |
device | Device to use for training ('cpu', 'cuda', 'cuda:0', etc.). If None, automatically selects GPU if available, otherwise CPU. Default is None. TYPE: |
dataset_path | Path to the manga dataset file. If None, uses the default manga dataset path. Default is None. TYPE: |
include_light_novels | Whether to include light novels in the manga dataset. When False, entries identified as light novels based on their genres will be filtered out. Default is False. TYPE: |
Notes
- This constructor passes "manga" as the dataset_type to the parent class
- The method automatically creates the output directory if it doesn't exist
- The output path is constructed from the model name and "manga"
- After initialization, the manga dataset is prepared for training
- If include_light_novels is False, light novels will be filtered from the dataset
Source code in src/training/manga_trainer.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
|
create_query_variations ¶
Create manga-specific variations of base queries to improve training robustness.
This method overrides the parent class implementation to generate query variations specifically tailored for manga search, using templates that reflect how users typically search for manga content (e.g., "Looking for manga about...", "Manga similar to...").
The variations help the model learn to recognize the same manga-related intent expressed in different ways, making it more robust to real-world search queries.
PARAMETER | DESCRIPTION |
---|---|
base_queries | List of original query strings (typically manga titles or descriptions) that will be used as the basis for generating variations. TYPE: |
n_variations | Number of manga-specific variations to create for each base query. If this exceeds the number of available templates, all templates will be used. Default is 7. TYPE: |
RETURNS | DESCRIPTION |
---|---|
List[str] | List[str]: A combined list containing both the original queries and their manga-specific variations. The length will be approximately len(base_queries) * (1 + n_variations), but may be less if n_variations exceeds the number of available templates. |
Example
# Create variations of manga titles
titles = ["One Piece", "Berserk", "Chainsaw Man"]
trainer = MangaModelTrainer()
variations = trainer.create_query_variations(titles, n_variations=3)
# Print all variations
for var in variations:
print(var)
# Example output:
# One Piece
# Looking for manga about One Piece
# I want to read manga with One Piece
# Find me manga where One Piece
# Berserk
# ...etc.
Notes
- The method always includes the original queries in the returned list
- Templates are selected randomly for each query
- All templates include the word "manga" to help the model recognize manga-specific search patterns
- This manga-specific implementation provides better training examples than the generic implementation in the parent class
- The manga templates focus on reading rather than watching (compared to anime)
Source code in src/training/manga_trainer.py
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 |
|
Dataset¶
Dataset implementation for cross-encoder training:
src.training.dataset.InputExampleDataset ¶
Bases: Dataset
PyTorch Dataset wrapper for a collection of SentenceTransformers InputExamples.
This dataset class adapts a list of InputExample objects (from SentenceTransformers) to be compatible with PyTorch's data loading utilities. It enables efficient batch processing during training and evaluation of cross-encoder models.
InputExamples typically contain: - A pair of texts (query and document) - A label indicating relevance or similarity - An optional identifier
This dataset implementation allows seamless integration with PyTorch's DataLoader for efficient batching, shuffling, and parallel data loading during training.
ATTRIBUTE | DESCRIPTION |
---|---|
examples | A list of InputExample objects containing the text pairs and labels for training or evaluation.
|
Example
from sentence_transformers import InputExample
from torch.utils.data import DataLoader
# Create example data
examples = [
InputExample(texts=['anime query', 'anime description'], label=1.0),
InputExample(texts=['unrelated query', 'anime description'], label=0.0),
# ... more examples
]
# Create dataset
dataset = InputExampleDataset(examples)
# Create DataLoader for training
train_dataloader = DataLoader(dataset, batch_size=16, shuffle=True)
# Use in training loop
for batch in train_dataloader:
# Process batch...
pass
PARAMETER | DESCRIPTION |
---|---|
examples | List of InputExample objects from SentenceTransformers. Each example should contain a pair of texts and a label. For cross-encoder training, each example typically contains: - texts[0]: The query text - texts[1]: The document text - label: A float value indicating relevance (typically 0 to 1) TYPE: |
Source code in src/training/dataset.py
__getitem__ ¶
Retrieve an example by its index.
This method is required by PyTorch's Dataset interface and is called by DataLoader during batch generation. It retrieves a single example by its index in the examples list.
PARAMETER | DESCRIPTION |
---|---|
idx | Integer index of the example to retrieve, must be in range 0 <= idx < len(self). TYPE: |
RETURNS | DESCRIPTION |
---|---|
InputExample | The example at the specified index, containing text pairs and a label. TYPE: |
RAISES | DESCRIPTION |
---|---|
IndexError | If idx is out of bounds for the examples list. |
Source code in src/training/dataset.py
__len__ ¶
Return the number of examples in the dataset.
This method is required by PyTorch's Dataset interface and is called by DataLoader to determine the size of the dataset and the number of batches.
RETURNS | DESCRIPTION |
---|---|
int | The total number of examples in the dataset. TYPE: |
Source code in src/training/dataset.py
Training Utilities¶
Helper functions for model training:
Training Utilities¶
Utility functions for training and fine-tuning cross-encoder models.
This module provides specialized utility functions for training, evaluating, and optimizing models in the anime/manga search application. It includes functionality for text preprocessing, device management, and optimization settings that are specifically tailored for cross-encoder model training.
Features¶
- Random seed initialization for reproducible experiments
- Device detection and configuration for CPU/GPU training
- Efficient batch text truncation for handling large text pairs
- Data parsing utilities for handling list data from datasets
- Default training parameters for common scenarios
Usage Context¶
These utilities are primarily used in:
- Model fine-tuning workflows
- Training script configuration
- Dataset preprocessing for training
The functions work together to provide a consistent environment for model training and help manage the complexities of preparing text data for transformer models.
DEFAULT_BATCH_SIZE module-attribute
¶
Default training batch size.
This batch size works well on most consumer GPUs with 8GB+ VRAM. Adjust based on available memory - larger batches generally provide more stable training but require more memory.
DEFAULT_EPOCHS module-attribute
¶
Default number of training epochs.
The model will iterate over the training data this many times. For cross-encoder models, 3 epochs is often sufficient to get good performance while avoiding overfitting.
DEFAULT_EVAL_STEPS module-attribute
¶
Default number of steps between model evaluations during training.
Controls how frequently the model is evaluated on the validation set.
DEFAULT_LEARNING_RATE module-attribute
¶
Default learning rate for fine-tuning.
A conservative learning rate that works well for most cross-encoder fine-tuning. Smaller than typical learning rates for training from scratch to avoid disrupting pre-trained weights.
DEFAULT_MAX_SAMPLES module-attribute
¶
Default maximum number of training samples to use.
Limits the training dataset size to avoid excessive training times for large datasets. Set to None to use the entire dataset.
DEFAULT_WARMUP_STEPS module-attribute
¶
Default number of learning rate warmup steps.
Learning rate starts at a low value and gradually increases to the full learning rate over this many steps, which helps with training stability.
MODEL_SAVE_PATH module-attribute
¶
Path where fine-tuned models are saved.
batch_truncate_text_pairs ¶
batch_truncate_text_pairs(text_pairs: List[Tuple[str, str]], tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast], max_length: int = 512, batch_size: int = 128) -> List[Tuple[str, str]]
Efficiently truncate multiple text pairs to fit within a specified token length.
This function processes a large list of text pairs (query, text) and truncates them to fit within the model's maximum sequence length. It uses a batch processing approach for efficiency and preserves as much of the query (text_a) as possible, truncating the document (text_b) to fit the remaining space.
The truncation process: 1. Tokenizes all text_a entries to calculate their token lengths 2. For each pair, reserves tokens for text_a plus special tokens 3. Allocates remaining tokens for text_b and truncates as needed 4. Performs validation checks on a sample of results to ensure compliance
PARAMETER | DESCRIPTION |
---|---|
text_pairs | List of tuples, each containing two strings (text_a, text_b). Typically, text_a is a query and text_b is a document or longer text. TYPE: |
tokenizer | The tokenizer that will be used with the model. Must be a transformers PreTrainedTokenizer or PreTrainedTokenizerFast instance compatible with the target model. TYPE: |
max_length | Maximum allowed sequence length in tokens (including all special tokens). Default is 512, which is common for many transformer models. TYPE: |
batch_size | Number of text pairs to process in each batch. Higher values increase memory usage but improve processing speed. Default is 128. TYPE: |
RETURNS | DESCRIPTION |
---|---|
List[Tuple[str, str]] | List[Tuple[str, str]]: A list of truncated text pairs, where each text_b has been truncated as needed to fit within the max_length constraint when combined with its text_a. |
Example
from transformers import AutoTokenizer
# Load a tokenizer
tokenizer = AutoTokenizer.from_pretrained("cross-encoder/ms-marco-MiniLM-L-6-v2")
# Sample text pairs (query, document)
text_pairs = [
("short query", "very long document text that exceeds the limit..."),
("another query", "another document that's also quite long...")
]
# Truncate to fit model's constraints
truncated_pairs = batch_truncate_text_pairs(
text_pairs=text_pairs,
tokenizer=tokenizer,
max_length=128, # Short for example purposes
batch_size=32
)
Notes
- The function prioritizes preserving text_a (usually the query) completely
- Only text_b is truncated unless absolutely necessary
- The function includes a double-check mechanism that samples some pairs to verify they actually fit within max_length
- Very long text_a entries might result in empty text_b if there's no space left
- The function uses the @handle_exceptions decorator for error handling
Source code in src/training/utils.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
|
get_device ¶
Determine the appropriate computing device for model training and inference.
This function selects the best available device for running models, defaulting to CUDA (GPU) if available, and falling back to CPU if not. It also allows for explicitly specifying a device if needed.
PARAMETER | DESCRIPTION |
---|---|
device | Optional string specifying the device to use. If provided, this overrides the automatic detection. Valid values include 'cpu', 'cuda', 'cuda:0', etc. Default is None, which triggers automatic detection. TYPE: |
RETURNS | DESCRIPTION |
---|---|
str | A string identifier for the device to use, compatible with PyTorch's device specification format (e.g., 'cuda', 'cpu', 'cuda:1'). TYPE: |
Example
Notes
- CUDA device is only returned if PyTorch can access CUDA
- The function doesn't check for specific CUDA device availability beyond what torch.cuda.is_available() provides
- For multi-GPU setups, you may want to explicitly specify a device or implement more sophisticated device selection logic
Source code in src/training/utils.py
parse_list_column ¶
Parse a list column from a dataset that may be stored as a string representation.
This function handles various formats of list data that may come from CSV or DataFrame columns, converting them to Python lists. It handles:
- String representations of lists like "[item1, item2, item3]"
- Already parsed list objects
- Single string values (converted to a single-item list)
- None or NaN values (converted to empty list)
PARAMETER | DESCRIPTION |
---|---|
column_value | The value to parse, which could be a string representation of a list, an actual list object, a single string, or a missing value (None/NaN). TYPE: |
RETURNS | DESCRIPTION |
---|---|
List[str] | List[str]: A list of strings parsed from the input. Returns an empty list for None or NaN values. |
Example
Notes
- Uses ast.literal_eval to safely parse string representations of lists
- Falls back to comma splitting if literal_eval fails
- Handles missing values (None, NaN) by returning an empty list
- Non-string, non-list inputs that aren't NaN will result in an empty list
Source code in src/training/utils.py
setup_random_seeds ¶
Set random seeds for reproducibility across Python, NumPy, and PyTorch.
This function sets consistent random seeds for all random number generators used in the training process, ensuring that experiments can be reproduced with the same randomization patterns. It sets seeds for:
- Python's random module
- NumPy's random number generator
- PyTorch's CPU random number generator
- PyTorch's GPU random number generators (if available)
PARAMETER | DESCRIPTION |
---|---|
seed | Integer value to use as the random seed. Default is 42, which is a common choice for reproducible machine learning experiments. TYPE: |
RETURNS | DESCRIPTION |
---|---|
None | This function doesn't return a value but sets global random states. TYPE: |
Example
Notes
- Using the same seed guarantees the same random sequence across runs
- Different hardware or PyTorch versions might still produce variations
- For full reproducibility, also set deterministic algorithms in PyTorch configurations and control the environment more strictly