Config¶
Configuration management for TorchLingo.
The Config class provides a centralized way to manage hyperparameters, file paths, and feature toggles. All TorchLingo functions accept an optional config parameter for customization.
Quick Start¶
from torchlingo.config import Config, get_default_config
# Use defaults
config = get_default_config()
# Customize
config = Config(
batch_size=64,
learning_rate=1e-4,
d_model=512,
)
# Pass to functions
dataset = NMTDataset("data.tsv", config=config)
model = SimpleTransformer(..., config=config)
API Reference¶
Config
¶
Config(base_dir: Optional[Path] = None, data_dir: Optional[Path] = None, checkpoint_dir: Optional[Path] = None, output_dir: Optional[Path] = None, data_format: str = 'tsv', src_col: str = 'src', tgt_col: str = 'tgt', src_tok_col: str = 'src_tokenized', tgt_tok_col: str = 'tgt_tokenized', train_file: Optional[Path] = None, val_file: Optional[Path] = None, test_file: Optional[Path] = None, raw_data_file: Optional[Path] = None, use_sentencepiece: bool = False, sentencepiece_model_prefix: Optional[str] = None, sentencepiece_model: Optional[str] = None, sentencepiece_vocab: Optional[str] = None, sentencepiece_src_model_prefix: Optional[str] = None, sentencepiece_tgt_model_prefix: Optional[str] = None, sentencepiece_src_model: Optional[str] = None, sentencepiece_tgt_model: Optional[str] = None, sentencepiece_src_vocab: Optional[str] = None, sentencepiece_tgt_vocab: Optional[str] = None, vocab_size: int = 32000, min_freq: int = 2, sp_model_type: str = 'bpe', sp_character_coverage: float = 1.0, sp_normalization_rule_name: str = 'nmt_nfkc', back_trans_src: Optional[Path] = None, back_trans_tgt: Optional[Path] = None, combined_train_src: Optional[Path] = None, combined_train_tgt: Optional[Path] = None, reverse_model_checkpoint: Optional[Path] = None, multi_train_file: Optional[Path] = None, multi_val_file: Optional[Path] = None, test_en_x_file: Optional[Path] = None, test_x_en_file: Optional[Path] = None, lang_tag_en_to_x: str = '<2X>', lang_tag_x_to_en: str = '<2E>', d_model: int = 512, n_heads: int = 8, num_encoder_layers: int = 6, num_decoder_layers: int = 6, d_ff: int = 2048, dropout: float = 0.1, max_seq_length: int = 512, lstm_emb_dim: int = 256, lstm_hidden_dim: int = 512, lstm_num_layers: int = 2, lstm_dropout: float = 0.2, use_packed_projection: bool = False, use_scaled_dot_product_attention: bool = False, tie_embeddings: bool = False, use_compile: bool = False, pad_token: str = '<pad>', unk_token: str = '<unk>', sos_token: str = '<sos>', eos_token: str = '<eos>', pad_idx: int = 0, unk_idx: int = 1, sos_idx: int = 2, eos_idx: int = 3, batch_size: int = 64, num_steps: int = 100000, step_limit: Optional[int] = None, learning_rate: float = 0.0001, adam_betas: tuple = (0.9, 0.98), adam_eps: float = 1e-09, weight_decay: float = 0.0001, warmup_steps: int = 4000, scheduler_type: str = 'cosine', scheduler_patience: int = 3, label_smoothing: float = 0.1, use_bucketing: bool = False, bucket_boundaries: Optional[list] = None, grad_clip: float = 1.0, val_interval: int = 1000, save_interval: int = 5000, log_interval: int = 100, patience: int = 10, checkpoint_path: Optional[Path] = None, last_checkpoint_path: Optional[Path] = None, beam_size: int = 5, max_decode_length: int = 200, length_penalty: float = 0.6, use_greedy: bool = False, output_translations: Optional[Path] = None, output_scores: Optional[Path] = None, device: Optional[str] = None, num_workers: int = 4, seed: int = 42, train_ratio: float = 0.8, val_ratio: float = 0.1, use_tensorboard: bool = False, tensorboard_dir: Optional[Path] = None, experiment_name: str = 'baseline', src_lang: str = 'eng', tgt_lang: str = 'deu')
Instantiable configuration container for TorchLingo training/inference.
This class allows you to create multiple independent config instances, each with its own hyperparameters and settings. Pass a Config instance to train(), evaluate(), or translate() functions.
Note
All attributes correspond to the configuration parameters documented above.
Examples:
>>> # Custom configuration with specific hyperparameters
>>> cfg = Config(batch_size=32, learning_rate=1e-5, beam_size=3)
>>> # Deep copy for experiments
>>> cfg_exp1 = cfg.copy()
>>> cfg_exp1.learning_rate = 5e-5
>>> # cfg and cfg_exp1 are independent
All parameters are optional. If not provided, defaults from the module-level constants above are used.
Source code in src/torchlingo/config.py
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 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 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 | |
to_dict
¶
Convert config to a dictionary for logging and serialization.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with all config attributes (excluding private attributes). |
Source code in src/torchlingo/config.py
get_default_config
¶
get_default_config() -> Config
Return a new Config object initialized with module-level defaults.
For experiments that require isolated configs, this function now returns a fresh instance each call, seeded from the current module-level values.
Returns:
| Type | Description |
|---|---|
Config
|
A new Config instance. |
Source code in src/torchlingo/config.py
Configuration Categories¶
Directory Paths¶
| Parameter | Default | Description |
|---|---|---|
data_dir |
src/data |
Data files directory |
checkpoint_dir |
src/checkpoints |
Model checkpoints |
output_dir |
src/outputs |
Generated outputs |
Data Settings¶
| Parameter | Default | Description |
|---|---|---|
data_format |
"tsv" |
File format: tsv, csv, parquet, json, txt |
src_col |
"src" |
Source column name |
tgt_col |
"tgt" |
Target column name |
Vocabulary Settings¶
| Parameter | Default | Description |
|---|---|---|
min_freq |
2 |
Minimum token frequency |
vocab_size |
32000 |
Target vocab size (SentencePiece) |
use_sentencepiece |
False |
Use subword tokenization |
Special Tokens¶
| Parameter | Default | Description |
|---|---|---|
pad_token |
"<pad>" |
Padding token |
unk_token |
"<unk>" |
Unknown token |
sos_token |
"<sos>" |
Start of sequence |
eos_token |
"<eos>" |
End of sequence |
pad_idx |
0 |
Padding index |
unk_idx |
1 |
Unknown index |
sos_idx |
2 |
SOS index |
eos_idx |
3 |
EOS index |
Model Architecture¶
| Parameter | Default | Description |
|---|---|---|
d_model |
512 |
Transformer hidden dimension |
n_heads |
8 |
Attention heads |
num_encoder_layers |
6 |
Encoder depth |
num_decoder_layers |
6 |
Decoder depth |
d_ff |
2048 |
Feed-forward dimension |
dropout |
0.1 |
Dropout rate |
LSTM Settings¶
| Parameter | Default | Description |
|---|---|---|
lstm_emb_dim |
256 |
Embedding dimension |
lstm_hidden_dim |
512 |
Hidden dimension |
lstm_num_layers |
2 |
Number of layers |
lstm_dropout |
0.1 |
Dropout rate |
Training Settings¶
| Parameter | Default | Description |
|---|---|---|
batch_size |
64 |
Batch size |
learning_rate |
1e-4 |
Learning rate |
max_seq_length |
128 |
Maximum sequence length |
num_epochs |
10 |
Training epochs |
scheduler_type |
"cosine" |
LR scheduler: "cosine", "plateau", "transformer", "noam", or "none" |
scheduler_patience |
3 |
Validations without improvement before plateau scheduler halves the LR |
warmup_steps |
4000 |
Warmup steps for cosine, transformer, and noam schedulers |
Experiment Tracking (TensorBoard)¶
| Parameter | Default | Description |
|---|---|---|
use_tensorboard |
False |
Enable TensorBoard logging |
tensorboard_dir |
./runs |
Directory for TensorBoard event files |
experiment_name |
"baseline" |
Experiment name (becomes subdirectory in tensorboard_dir) |
log_interval |
100 |
Steps between logging metrics |
val_interval |
1000 |
Steps between validation checks |
save_interval |
5000 |
Steps between checkpoint saves |
Examples¶
Creating Custom Configs¶
# Small model for testing
test_config = Config(
d_model=64,
n_heads=2,
num_encoder_layers=1,
num_decoder_layers=1,
batch_size=8,
)
# Production model
prod_config = Config(
d_model=512,
n_heads=8,
num_encoder_layers=6,
num_decoder_layers=6,
batch_size=64,
learning_rate=5e-5,
)
Cloning and Modifying¶
base = get_default_config()
experiment = base.clone()
experiment.learning_rate = 1e-5
experiment.batch_size = 128
Saving and Loading¶
import json
# Save to JSON
config = Config(batch_size=32)
with open("config.json", "w") as f:
json.dump(config.to_dict(), f)
# Load from JSON
with open("config.json", "r") as f:
config = Config.from_dict(json.load(f))
Module Constants¶
For maximum compatibility, module-level constants are also available:
from torchlingo import config
print(config.BATCH_SIZE) # Default batch size
print(config.DATA_DIR) # Data directory path
print(config.PAD_IDX) # Padding token index
Prefer Config Objects
Module constants are read-only. For customization, always use Config objects.