{"id":34519862,"url":"https://github.com/omarkamali/craft","last_synced_at":"2025-12-26T06:02:54.635Z","repository":{"id":329596133,"uuid":"1119850270","full_name":"omarkamali/craft","owner":"omarkamali","description":"CRAFT: Contrastive Representation Aware Fine-Tuning toolkit","archived":false,"fork":false,"pushed_at":"2025-12-20T15:48:03.000Z","size":235,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-12-22T18:09:14.246Z","etag":null,"topics":["contrastive-learning","fine-tuning","jupyter-notebook","llm","ml-training","pytorch","representation-learning","toolkit"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/omarkamali.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-20T00:57:21.000Z","updated_at":"2025-12-20T15:46:22.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/omarkamali/craft","commit_stats":null,"previous_names":["omarkamali/craft"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/omarkamali/craft","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/omarkamali%2Fcraft","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/omarkamali%2Fcraft/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/omarkamali%2Fcraft/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/omarkamali%2Fcraft/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/omarkamali","download_url":"https://codeload.github.com/omarkamali/craft/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/omarkamali%2Fcraft/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28020012,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-12-25T02:00:05.988Z","response_time":58,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["contrastive-learning","fine-tuning","jupyter-notebook","llm","ml-training","pytorch","representation-learning","toolkit"],"created_at":"2025-12-24T04:39:47.872Z","updated_at":"2025-12-25T05:01:32.953Z","avatar_url":"https://github.com/omarkamali.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# CRAFT · Contrastive Representation Aware Fine-Tuning\n\nCRAFT is a library that layers a contrastive InfoNCE objective on top of standard SFT and\npreference-optimization trainers. It provides:\n\n- **Composable losses** – configurable InfoNCE loss with projection/pooling and weighted\n  blending against supervised losses via `craft_alpha`.\n- **Mixed data loading** – automated cycling of SFT and contrastive batches according to a\n  configurable `craft_beta` ratio, with optional auto-tuning via `craft_beta_mode`.\n- **Trainer wrappers** – drop-in replacements for TRL's SFT/ORPO/GRPO/PPO/DPO trainers plus\n  utilities for plain `transformers.Trainer` usage.\n- **Metrics** – contrastive accuracy, representation consistency, and reference tracking.\n- **Dataset utilities** – helpers for paired datasets or self-aligned positives, plus a\n  default collator ready for mixed InfoNCE/SFT batches.\n- **Flexible length matching** – options to oversample, cap, auto-adjust ratios, or raise\n  if SFT and contrastive lengths diverge, alongside per-loader batch size overrides.\n\n## Installation\n\n```bash\n# Editable install with testing extras\nuv pip install -e '.[test]'\n\n# Optional dependency groups\nuv pip install -e '.[trl]'    # TRL trainers\nuv pip install -e '.[hf]'     # transformers integration only\nuv pip install -e '.[peft]'   # LoRA/PEFT examples\nuv pip install -e '.[all]'    # everything\n```\n\n## Package layout\n\n```\ncraft/\n  ├── config.py     # CRAFT config mixin + TRL-specific configs\n  ├── data.py       # Dataset bundle, collator, mixed dataloader\n  ├── losses.py     # InfoNCELoss + loss combination helpers\n  ├── metrics.py    # Metric utilities and EMA helpers\n  ├── trainers.py   # CRAFT trainer mixin + TRL wrappers\n  └── __init__.py   # Public exports\n```\n\n## What's New\n\n### Custom Data Loaders\n\nCRAFT now supports custom PyTorch `DataLoader` instances for both SFT and contrastive training, giving you more control over batching, sampling, and collation logic.\n\n```python\ntrainer = CRAFTSFTTrainer(\n    model=model,\n    args=args,\n    train_dataset=sft_dataset,  # Still required for length calculations\n    craft_bundle=bundle,\n    craft_sft_loader=custom_sft_loader,          # Custom SFT loader\n    craft_contrastive_loader=custom_contrast_loader  # Custom contrastive loader\n)\n```\n\n### Enhanced Self-align Validation\n\nWhen using `strategy=\"self_align\"`, CRAFT now performs additional validation to ensure your data is properly formatted:\n\n- Validates presence of either `labels` or `assistant_mask` in SFT batches\n- Ensures at least one token is marked as an assistant token\n- Provides clear error messages for common configuration issues\n\n```python\n# Example of valid self-align batch\n{\n    \"input_ids\": torch.tensor([...]),\n    \"attention_mask\": torch.tensor([...]),\n    \"labels\": torch.tensor([-100, -100, 1234, 5678, -100]),  # Assistant tokens where labels != -100\n    # OR\n    \"assistant_mask\": torch.tensor([0, 0, 1, 1, 0])  # 1 marks assistant tokens\n}\n```\n\n## Quick start\n\n```python\nfrom transformers import AutoModelForCausalLM\nfrom craft.config import CRAFTSFTConfig\nfrom craft.data import CRAFTCollator, make_craft_datasets\nfrom craft.trainers import CRAFTSFTTrainer\n\n# Assume `sft_dataset` and `contrastive_dataset` are tokenized datasets with the\n# appropriate columns (`input_ids`, `attention_mask`, optional *_tgt columns).\n\nbundle = make_craft_datasets(\n    sft_dataset,\n    contrastive_dataset=contrastive_dataset,\n    strategy=\"paired_dataset\",\n)\n\nmodel = AutoModelForCausalLM.from_pretrained(\"HuggingFaceH4/zephyr-7b-beta\")\n\nargs = CRAFTSFTConfig(\n    output_dir=\"./outputs\",\n    per_device_train_batch_size=2,\n    gradient_accumulation_steps=8,\n    craft_alpha=0.6,\n    craft_beta=0.5,\n)\n\ntrainer = CRAFTSFTTrainer(\n    model=model,\n    args=args,\n    train_dataset=sft_dataset,\n    craft_bundle=bundle,\n    data_collator=CRAFTCollator(),\n)\n\ntrainer.train()\n```\n\n### Length matching \u0026 batching strategies\n\nCRAFT lets you control how supervised (SFT) and contrastive datasets are balanced:\n\n- `craft_length_strategy=\"oversample\"` – loop the shorter loader (default).\n- `\"cap\"` – stop when either loader exhausts, keeping epochs perfectly aligned.\n- `\"auto_beta\"` – cap like above **and** recompute `craft_beta` from observed batch counts.\n- `\"error\"` – raise if lengths diverge, useful for deterministic experiments.\n\nCombine this with `craft_contrastive_batch_size` to decouple batch sizes:\n\n```python\nconfig = CRAFTSFTConfig(\n    output_dir=\"./outputs\",\n    per_device_train_batch_size=2,\n    craft_contrastive_batch_size=4,\n    craft_beta=0.5,\n    craft_beta_mode=\"auto\",\n    craft_length_strategy=\"auto_beta\",\n)\n```\n\nThese knobs are honoured by all `CRAFT*Trainer` classes and the `CRAFTMixedDataLoader`.\n\n## Notebooks\n\nSix notebooks under `packages/craft/notebooks` cover end-to-end workflows:\n\n1. **01-craft-basic-sft** – minimal CRAFTSFTTrainer run with paired datasets.\n2. **02-craft-best-practices** – conversation packing, assistant masking, LoRA.\n3. **03a-craft-loss-transformers-trainer** – integrate `InfoNCELoss` with vanilla\n   `transformers.Trainer`.\n4. **03b-craft-trl-sft** – TRL SFTTrainer wrapper with CRAFT metrics.\n5. **03c-craft-trl-orpo** – ORPO preference optimisation with contrastive batches.\n6. **04-craft-qlora-translation-eval** – QLoRA fine-tune of `unsloth/gemma-3-270M-it`\n   on Flores translations, with before/after BLEU, loss curves, and metric plots.\n\n## Testing\n\nCRAFT ships with a pytest suite covering losses, metrics, data utilities, and trainer mixins.\n\n```bash\nuv pip install -e '.[test]'\nuv run python -m pytest -q\n```\n\n## Contributing\n\n1. Add or update tests for new functionality.\n2. Run the lint/test suite before submitting patches.\n3. Update notebooks and documentation to reflect API changes.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fomarkamali%2Fcraft","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fomarkamali%2Fcraft","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fomarkamali%2Fcraft/lists"}