From b2f00ae58089e46fd644259de6d4a4654a4ac62a Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Wed, 29 Apr 2026 01:44:26 +0300 Subject: [PATCH 1/5] feat(site): multi-language user guide with markdown source + CI deploy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduces a /guide entry point sourced from per-language markdown under docs/usermanuals/. A small Python build (tools/build_usermanuals.py) compiles 6 languages × 53 topics into JS data files that the guide.html shell loads at runtime via hash-based routing, with sidebar nav, scroll-spy TOC, Cmd+K search, mermaid diagrams, and cross-language fallback to EN. Site i18n widened from EN/TR to EN/TR/DE/FR/ES/ZH. The legacy twin-span pattern was replaced with a data-i18n attribute system backed by translations.js; the seven existing public pages were rewritten accordingly and a globe-icon dropdown replaced the two-button toggle. Content delivered: 53/53 EN pages and 53/53 TR pages spanning getting-started, concepts, training, data, evaluation, compliance, operations, deployment, and reference. DE/FR/ES/ZH share the index and chrome translations and fall back to EN with a banner until their markdown is filled in. CI: - .github/workflows/site-deploy.yml — builds usermanuals + deploys site/ to GitHub Pages on push to main (Pages source must be set to "GitHub Actions"). - .github/workflows/usermanuals-validate.yml — verifies on PR that every page declared in _meta.yaml has at least an EN markdown source. Generated JS data files (site/js/usermanuals/*.js) are now .gitignored; CI rebuilds them fresh on every deploy. Local preview: run tools/build_usermanuals.py once, then any static server. Static-analyzer cleanup in i18n.js and main.js: Object.hasOwn replaces hasOwnProperty.call; per-language lookup goes through a switch helper instead of bracket access; data-i18n-html now renders via DOMParser + appendChild instead of innerHTML; var hoisting in initTheme; NodeList iterator in initHeroTyper. Co-Authored-By: Claude Opus 4.7 (1M context) --- .github/workflows/site-deploy.yml | 84 +++ .github/workflows/usermanuals-validate.yml | 48 ++ .gitignore | 6 + docs/usermanuals/_meta.yaml | 492 +++++++++++++ docs/usermanuals/en/compliance/annex-iv.md | 164 +++++ docs/usermanuals/en/compliance/audit-log.md | 142 ++++ docs/usermanuals/en/compliance/gdpr.md | 151 ++++ .../en/compliance/human-oversight.md | 164 +++++ docs/usermanuals/en/compliance/model-card.md | 159 ++++ docs/usermanuals/en/compliance/overview.md | 126 ++++ .../en/concepts/alignment-overview.md | 121 +++ .../en/concepts/choosing-trainer.md | 101 +++ docs/usermanuals/en/concepts/data-formats.md | 176 +++++ docs/usermanuals/en/data/audit.md | 161 ++++ docs/usermanuals/en/data/deduplication.md | 115 +++ docs/usermanuals/en/data/ingestion.md | 122 ++++ .../usermanuals/en/data/language-detection.md | 81 +++ docs/usermanuals/en/data/leakage.md | 121 +++ docs/usermanuals/en/data/pii-masking.md | 139 ++++ docs/usermanuals/en/data/quality-filter.md | 98 +++ docs/usermanuals/en/data/secrets.md | 131 ++++ docs/usermanuals/en/data/synthetic-data.md | 129 ++++ docs/usermanuals/en/deployment/chat.md | 140 ++++ .../en/deployment/deploy-targets.md | 215 ++++++ docs/usermanuals/en/deployment/gguf-export.md | 148 ++++ .../en/deployment/model-merging.md | 179 +++++ docs/usermanuals/en/evaluation/auto-revert.md | 142 ++++ docs/usermanuals/en/evaluation/benchmarks.md | 149 ++++ docs/usermanuals/en/evaluation/judge.md | 167 +++++ docs/usermanuals/en/evaluation/safety.md | 151 ++++ .../en/evaluation/trend-tracking.md | 130 ++++ .../en/getting-started/first-run.md | 146 ++++ .../en/getting-started/installation.md | 130 ++++ .../en/getting-started/introduction.md | 107 +++ .../en/getting-started/project-layout.md | 125 ++++ docs/usermanuals/en/operations/air-gap.md | 159 ++++ docs/usermanuals/en/operations/cicd.md | 197 +++++ docs/usermanuals/en/operations/docker.md | 149 ++++ .../en/operations/experiment-tracking.md | 143 ++++ docs/usermanuals/en/operations/gpu-cost.md | 143 ++++ .../en/operations/troubleshooting.md | 181 +++++ .../en/operations/vram-fit-check.md | 142 ++++ docs/usermanuals/en/operations/webhooks.md | 159 ++++ docs/usermanuals/en/reference/cli.md | 219 ++++++ .../usermanuals/en/reference/configuration.md | 318 ++++++++ docs/usermanuals/en/reference/exit-codes.md | 134 ++++ .../en/reference/yaml-templates.md | 356 +++++++++ docs/usermanuals/en/training/distributed.md | 148 ++++ docs/usermanuals/en/training/dpo.md | 228 ++++++ docs/usermanuals/en/training/galore.md | 92 +++ docs/usermanuals/en/training/grpo.md | 139 ++++ docs/usermanuals/en/training/kto.md | 91 +++ docs/usermanuals/en/training/long-context.md | 140 ++++ docs/usermanuals/en/training/lora.md | 146 ++++ docs/usermanuals/en/training/orpo.md | 86 +++ docs/usermanuals/en/training/sft.md | 141 ++++ docs/usermanuals/en/training/simpo.md | 96 +++ docs/usermanuals/tr/compliance/annex-iv.md | 164 +++++ docs/usermanuals/tr/compliance/audit-log.md | 142 ++++ docs/usermanuals/tr/compliance/gdpr.md | 151 ++++ .../tr/compliance/human-oversight.md | 164 +++++ docs/usermanuals/tr/compliance/model-card.md | 160 ++++ docs/usermanuals/tr/compliance/overview.md | 111 +++ .../tr/concepts/alignment-overview.md | 121 +++ .../tr/concepts/choosing-trainer.md | 101 +++ docs/usermanuals/tr/concepts/data-formats.md | 142 ++++ docs/usermanuals/tr/data/audit.md | 147 ++++ docs/usermanuals/tr/data/deduplication.md | 115 +++ docs/usermanuals/tr/data/ingestion.md | 122 ++++ .../usermanuals/tr/data/language-detection.md | 81 +++ docs/usermanuals/tr/data/leakage.md | 121 +++ docs/usermanuals/tr/data/pii-masking.md | 139 ++++ docs/usermanuals/tr/data/quality-filter.md | 98 +++ docs/usermanuals/tr/data/secrets.md | 131 ++++ docs/usermanuals/tr/data/synthetic-data.md | 129 ++++ docs/usermanuals/tr/deployment/chat.md | 140 ++++ .../tr/deployment/deploy-targets.md | 215 ++++++ docs/usermanuals/tr/deployment/gguf-export.md | 148 ++++ .../tr/deployment/model-merging.md | 179 +++++ docs/usermanuals/tr/evaluation/auto-revert.md | 142 ++++ docs/usermanuals/tr/evaluation/benchmarks.md | 149 ++++ docs/usermanuals/tr/evaluation/judge.md | 163 +++++ docs/usermanuals/tr/evaluation/safety.md | 151 ++++ .../tr/evaluation/trend-tracking.md | 130 ++++ .../tr/getting-started/first-run.md | 146 ++++ .../tr/getting-started/installation.md | 130 ++++ .../tr/getting-started/introduction.md | 107 +++ .../tr/getting-started/project-layout.md | 123 ++++ docs/usermanuals/tr/operations/air-gap.md | 159 ++++ docs/usermanuals/tr/operations/cicd.md | 196 +++++ docs/usermanuals/tr/operations/docker.md | 149 ++++ .../tr/operations/experiment-tracking.md | 143 ++++ docs/usermanuals/tr/operations/gpu-cost.md | 143 ++++ .../tr/operations/troubleshooting.md | 181 +++++ .../tr/operations/vram-fit-check.md | 142 ++++ docs/usermanuals/tr/operations/webhooks.md | 159 ++++ docs/usermanuals/tr/reference/cli.md | 219 ++++++ .../usermanuals/tr/reference/configuration.md | 301 ++++++++ docs/usermanuals/tr/reference/exit-codes.md | 117 +++ .../tr/reference/yaml-templates.md | 356 +++++++++ docs/usermanuals/tr/training/distributed.md | 148 ++++ docs/usermanuals/tr/training/dpo.md | 202 ++++++ docs/usermanuals/tr/training/galore.md | 92 +++ docs/usermanuals/tr/training/grpo.md | 131 ++++ docs/usermanuals/tr/training/kto.md | 88 +++ docs/usermanuals/tr/training/long-context.md | 140 ++++ docs/usermanuals/tr/training/lora.md | 144 ++++ docs/usermanuals/tr/training/orpo.md | 82 +++ docs/usermanuals/tr/training/sft.md | 124 ++++ docs/usermanuals/tr/training/simpo.md | 91 +++ site/compliance.html | 224 ++---- site/contact.html | 151 ++-- site/css/style.css | 686 +++++++++++++++++- site/features.html | 209 +++--- site/guide.html | 144 ++++ site/index.html | 457 ++++-------- site/js/guide.js | 628 ++++++++++++++++ site/js/i18n.js | 50 +- site/js/main.js | 73 +- site/js/translations.js | 104 +++ site/privacy.html | 157 +--- site/quickstart.html | 145 ++-- site/terms.html | 147 +--- tools/build_usermanuals.py | 387 ++++++++++ 124 files changed, 18872 insertions(+), 1026 deletions(-) create mode 100644 .github/workflows/site-deploy.yml create mode 100644 .github/workflows/usermanuals-validate.yml create mode 100644 docs/usermanuals/_meta.yaml create mode 100644 docs/usermanuals/en/compliance/annex-iv.md create mode 100644 docs/usermanuals/en/compliance/audit-log.md create mode 100644 docs/usermanuals/en/compliance/gdpr.md create mode 100644 docs/usermanuals/en/compliance/human-oversight.md create mode 100644 docs/usermanuals/en/compliance/model-card.md create mode 100644 docs/usermanuals/en/compliance/overview.md create mode 100644 docs/usermanuals/en/concepts/alignment-overview.md create mode 100644 docs/usermanuals/en/concepts/choosing-trainer.md create mode 100644 docs/usermanuals/en/concepts/data-formats.md create mode 100644 docs/usermanuals/en/data/audit.md create mode 100644 docs/usermanuals/en/data/deduplication.md create mode 100644 docs/usermanuals/en/data/ingestion.md create mode 100644 docs/usermanuals/en/data/language-detection.md create mode 100644 docs/usermanuals/en/data/leakage.md create mode 100644 docs/usermanuals/en/data/pii-masking.md create mode 100644 docs/usermanuals/en/data/quality-filter.md create mode 100644 docs/usermanuals/en/data/secrets.md create mode 100644 docs/usermanuals/en/data/synthetic-data.md create mode 100644 docs/usermanuals/en/deployment/chat.md create mode 100644 docs/usermanuals/en/deployment/deploy-targets.md create mode 100644 docs/usermanuals/en/deployment/gguf-export.md create mode 100644 docs/usermanuals/en/deployment/model-merging.md create mode 100644 docs/usermanuals/en/evaluation/auto-revert.md create mode 100644 docs/usermanuals/en/evaluation/benchmarks.md create mode 100644 docs/usermanuals/en/evaluation/judge.md create mode 100644 docs/usermanuals/en/evaluation/safety.md create mode 100644 docs/usermanuals/en/evaluation/trend-tracking.md create mode 100644 docs/usermanuals/en/getting-started/first-run.md create mode 100644 docs/usermanuals/en/getting-started/installation.md create mode 100644 docs/usermanuals/en/getting-started/introduction.md create mode 100644 docs/usermanuals/en/getting-started/project-layout.md create mode 100644 docs/usermanuals/en/operations/air-gap.md create mode 100644 docs/usermanuals/en/operations/cicd.md create mode 100644 docs/usermanuals/en/operations/docker.md create mode 100644 docs/usermanuals/en/operations/experiment-tracking.md create mode 100644 docs/usermanuals/en/operations/gpu-cost.md create mode 100644 docs/usermanuals/en/operations/troubleshooting.md create mode 100644 docs/usermanuals/en/operations/vram-fit-check.md create mode 100644 docs/usermanuals/en/operations/webhooks.md create mode 100644 docs/usermanuals/en/reference/cli.md create mode 100644 docs/usermanuals/en/reference/configuration.md create mode 100644 docs/usermanuals/en/reference/exit-codes.md create mode 100644 docs/usermanuals/en/reference/yaml-templates.md create mode 100644 docs/usermanuals/en/training/distributed.md create mode 100644 docs/usermanuals/en/training/dpo.md create mode 100644 docs/usermanuals/en/training/galore.md create mode 100644 docs/usermanuals/en/training/grpo.md create mode 100644 docs/usermanuals/en/training/kto.md create mode 100644 docs/usermanuals/en/training/long-context.md create mode 100644 docs/usermanuals/en/training/lora.md create mode 100644 docs/usermanuals/en/training/orpo.md create mode 100644 docs/usermanuals/en/training/sft.md create mode 100644 docs/usermanuals/en/training/simpo.md create mode 100644 docs/usermanuals/tr/compliance/annex-iv.md create mode 100644 docs/usermanuals/tr/compliance/audit-log.md create mode 100644 docs/usermanuals/tr/compliance/gdpr.md create mode 100644 docs/usermanuals/tr/compliance/human-oversight.md create mode 100644 docs/usermanuals/tr/compliance/model-card.md create mode 100644 docs/usermanuals/tr/compliance/overview.md create mode 100644 docs/usermanuals/tr/concepts/alignment-overview.md create mode 100644 docs/usermanuals/tr/concepts/choosing-trainer.md create mode 100644 docs/usermanuals/tr/concepts/data-formats.md create mode 100644 docs/usermanuals/tr/data/audit.md create mode 100644 docs/usermanuals/tr/data/deduplication.md create mode 100644 docs/usermanuals/tr/data/ingestion.md create mode 100644 docs/usermanuals/tr/data/language-detection.md create mode 100644 docs/usermanuals/tr/data/leakage.md create mode 100644 docs/usermanuals/tr/data/pii-masking.md create mode 100644 docs/usermanuals/tr/data/quality-filter.md create mode 100644 docs/usermanuals/tr/data/secrets.md create mode 100644 docs/usermanuals/tr/data/synthetic-data.md create mode 100644 docs/usermanuals/tr/deployment/chat.md create mode 100644 docs/usermanuals/tr/deployment/deploy-targets.md create mode 100644 docs/usermanuals/tr/deployment/gguf-export.md create mode 100644 docs/usermanuals/tr/deployment/model-merging.md create mode 100644 docs/usermanuals/tr/evaluation/auto-revert.md create mode 100644 docs/usermanuals/tr/evaluation/benchmarks.md create mode 100644 docs/usermanuals/tr/evaluation/judge.md create mode 100644 docs/usermanuals/tr/evaluation/safety.md create mode 100644 docs/usermanuals/tr/evaluation/trend-tracking.md create mode 100644 docs/usermanuals/tr/getting-started/first-run.md create mode 100644 docs/usermanuals/tr/getting-started/installation.md create mode 100644 docs/usermanuals/tr/getting-started/introduction.md create mode 100644 docs/usermanuals/tr/getting-started/project-layout.md create mode 100644 docs/usermanuals/tr/operations/air-gap.md create mode 100644 docs/usermanuals/tr/operations/cicd.md create mode 100644 docs/usermanuals/tr/operations/docker.md create mode 100644 docs/usermanuals/tr/operations/experiment-tracking.md create mode 100644 docs/usermanuals/tr/operations/gpu-cost.md create mode 100644 docs/usermanuals/tr/operations/troubleshooting.md create mode 100644 docs/usermanuals/tr/operations/vram-fit-check.md create mode 100644 docs/usermanuals/tr/operations/webhooks.md create mode 100644 docs/usermanuals/tr/reference/cli.md create mode 100644 docs/usermanuals/tr/reference/configuration.md create mode 100644 docs/usermanuals/tr/reference/exit-codes.md create mode 100644 docs/usermanuals/tr/reference/yaml-templates.md create mode 100644 docs/usermanuals/tr/training/distributed.md create mode 100644 docs/usermanuals/tr/training/dpo.md create mode 100644 docs/usermanuals/tr/training/galore.md create mode 100644 docs/usermanuals/tr/training/grpo.md create mode 100644 docs/usermanuals/tr/training/kto.md create mode 100644 docs/usermanuals/tr/training/long-context.md create mode 100644 docs/usermanuals/tr/training/lora.md create mode 100644 docs/usermanuals/tr/training/orpo.md create mode 100644 docs/usermanuals/tr/training/sft.md create mode 100644 docs/usermanuals/tr/training/simpo.md create mode 100644 site/guide.html create mode 100644 site/js/guide.js create mode 100644 tools/build_usermanuals.py diff --git a/.github/workflows/site-deploy.yml b/.github/workflows/site-deploy.yml new file mode 100644 index 00000000..04c3726e --- /dev/null +++ b/.github/workflows/site-deploy.yml @@ -0,0 +1,84 @@ +name: Deploy site + +# Build the user-manual content from docs/usermanuals/ and deploy the +# static `site/` directory to GitHub Pages. +# +# Trigger matrix +# -------------- +# * push to main on any path under site/, docs/usermanuals/, or +# tools/build_usermanuals.py — site is rebuilt and republished. +# * workflow_dispatch — manual rebuild button in the Actions UI. +# +# Pre-requisites in the repository settings +# ----------------------------------------- +# Settings → Pages → Build and deployment → Source: "GitHub Actions" +# +# Why a build job +# --------------- +# The site uses generated content under site/js/usermanuals/, compiled +# from markdown sources in docs/usermanuals/. The generated files are +# gitignored, so they have to be produced fresh on every deploy. + +on: + push: + branches: [main] + paths: + - "site/**" + - "docs/usermanuals/**" + - "tools/build_usermanuals.py" + - ".github/workflows/site-deploy.yml" + workflow_dispatch: + +# Pages deployments expect these permissions on the runner. +permissions: + contents: read + pages: write + id-token: write + +# Only one Pages deployment can run at a time per ref. Cancel-in-progress +# is intentionally false — we want the most recent commit to win, but +# without dropping an in-flight one mid-deploy. +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Install build dependencies + run: pip install markdown pyyaml + + - name: Compile user-manual markdown to JS + run: python3 tools/build_usermanuals.py + + - name: Verify the generated tree + run: | + test -f site/js/usermanuals/_index.js + test -f site/js/usermanuals/en.js + for lang in en tr de fr es zh; do + test -f "site/js/usermanuals/${lang}.js" || { echo "missing ${lang}.js"; exit 1; } + done + + - uses: actions/configure-pages@v5 + + - name: Upload Pages artifact + uses: actions/upload-pages-artifact@v3 + with: + path: site + + deploy: + needs: build + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/usermanuals-validate.yml b/.github/workflows/usermanuals-validate.yml new file mode 100644 index 00000000..985beb0a --- /dev/null +++ b/.github/workflows/usermanuals-validate.yml @@ -0,0 +1,48 @@ +name: Validate user-manuals + +# On pull requests that touch the user-manual sources or the build tool, +# verify the build script can compile every markdown file without errors +# and that every page declared in `_meta.yaml` has at least an English +# source. Catches structural problems before they hit main. + +on: + pull_request: + branches: [main] + paths: + - "docs/usermanuals/**" + - "tools/build_usermanuals.py" + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Install dependencies + run: pip install markdown pyyaml + + - name: Build user-manuals + run: python3 tools/build_usermanuals.py + + - name: Smoke-test that core pages have English content + # If somebody renamed a section in _meta.yaml without moving the + # markdown source, the build silently falls back to a placeholder. + # Fail the build instead so the PR author notices. + run: | + python3 - <<'PY' + import json, pathlib, re + src = pathlib.Path("site/js/usermanuals/en.js").read_text(encoding="utf-8") + # Each "missing": true entry is a page whose markdown source + # could not be found at all (no English fallback even). + missing = re.findall(r'"([^"]+)":\s*\{[^{}]*"missing":\s*true', src) + if missing: + print("ERROR: pages declared in _meta.yaml but missing markdown:") + for m in sorted(set(missing)): + print(f" - {m}") + raise SystemExit(1) + print("OK — every declared page has an English source.") + PY diff --git a/.gitignore b/.gitignore index 04040d89..4cdef8af 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,12 @@ docs/marketing/ docs/analysis/ +# Generated by tools/build_usermanuals.py — produced from +# docs/usermanuals//**/*.md during the CI deploy. Not committed; +# the GitHub Actions site-deploy workflow builds them fresh on every push. +# Local preview: run `python3 tools/build_usermanuals.py` first. +site/js/usermanuals/*.js + # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] diff --git a/docs/usermanuals/_meta.yaml b/docs/usermanuals/_meta.yaml new file mode 100644 index 00000000..e47445ba --- /dev/null +++ b/docs/usermanuals/_meta.yaml @@ -0,0 +1,492 @@ +# ForgeLM user-manual structure. +# +# This file defines the navigation tree for the user guide on the website. +# Source content lives under docs/usermanuals///.md +# and is compiled by tools/build_usermanuals.py into site/js/usermanuals/.js. +# +# `id` values must be lowercase, kebab-case, ASCII — they form URL fragments +# and filesystem paths. +# +# Page titles must exist for every supported language (en, tr, de, fr, es, zh). +# If a page's source markdown is missing for a language at build time, the +# English source is used as a fallback and the generated record is marked +# `fallback: true` so the site can show a "translation pending" banner. + +languages: [en, tr, de, fr, es, zh] +default_language: en + +sections: + - id: getting-started + icon: rocket + title: + en: Getting Started + tr: Başlarken + de: Erste Schritte + fr: Premiers pas + es: Primeros pasos + zh: 入门 + pages: + - id: introduction + title: + en: Introduction + tr: Tanıtım + de: Einführung + fr: Introduction + es: Introducción + zh: 简介 + - id: installation + title: + en: Installation + tr: Kurulum + de: Installation + fr: Installation + es: Instalación + zh: 安装 + - id: first-run + title: + en: Your First Run + tr: İlk Koşunuz + de: Ihr erster Lauf + fr: Votre première exécution + es: Su primera ejecución + zh: 你的第一次运行 + - id: project-layout + title: + en: Project Layout + tr: Proje Yapısı + de: Projektstruktur + fr: Structure du projet + es: Estructura del proyecto + zh: 项目结构 + + - id: concepts + icon: book + title: + en: Core Concepts + tr: Temel Kavramlar + de: Kernkonzepte + fr: Concepts fondamentaux + es: Conceptos fundamentales + zh: 核心概念 + pages: + - id: alignment-overview + title: + en: The Alignment Stack + tr: Alignment Yığını + de: Der Alignment-Stack + fr: La pile d'alignement + es: El stack de alignment + zh: 对齐栈 + - id: choosing-trainer + title: + en: Choosing a Trainer + tr: Trainer Seçimi + de: Trainer auswählen + fr: Choisir un trainer + es: Elegir un trainer + zh: 选择 trainer + - id: data-formats + title: + en: Dataset Formats + tr: Veri Seti Formatları + de: Dataset-Formate + fr: Formats de jeux de données + es: Formatos de dataset + zh: 数据集格式 + + - id: training + icon: cpu + title: + en: Training & Alignment + tr: Eğitim ve Alignment + de: Training & Alignment + fr: Entraînement et alignement + es: Entrenamiento y alignment + zh: 训练与对齐 + pages: + - id: sft + title: { en: SFT, tr: SFT, de: SFT, fr: SFT, es: SFT, zh: SFT } + - id: dpo + title: { en: DPO, tr: DPO, de: DPO, fr: DPO, es: DPO, zh: DPO } + - id: simpo + title: { en: SimPO, tr: SimPO, de: SimPO, fr: SimPO, es: SimPO, zh: SimPO } + - id: kto + title: { en: KTO, tr: KTO, de: KTO, fr: KTO, es: KTO, zh: KTO } + - id: orpo + title: { en: ORPO, tr: ORPO, de: ORPO, fr: ORPO, es: ORPO, zh: ORPO } + - id: grpo + title: { en: GRPO, tr: GRPO, de: GRPO, fr: GRPO, es: GRPO, zh: GRPO } + - id: lora + title: + en: LoRA, QLoRA, DoRA + tr: LoRA, QLoRA, DoRA + de: LoRA, QLoRA, DoRA + fr: LoRA, QLoRA, DoRA + es: LoRA, QLoRA, DoRA + zh: LoRA, QLoRA, DoRA + - id: galore + title: { en: GaLore, tr: GaLore, de: GaLore, fr: GaLore, es: GaLore, zh: GaLore } + - id: long-context + title: + en: Long Context + tr: Uzun Bağlam + de: Langer Kontext + fr: Long contexte + es: Contexto largo + zh: 长上下文 + - id: distributed + title: + en: Distributed Training + tr: Dağıtık Eğitim + de: Verteiltes Training + fr: Entraînement distribué + es: Entrenamiento distribuido + zh: 分布式训练 + + - id: data + icon: database + title: + en: Data + tr: Veri + de: Daten + fr: Données + es: Datos + zh: 数据 + pages: + - id: ingestion + title: + en: Document Ingestion + tr: Doküman Ingest'i + de: Dokumentenaufnahme + fr: Ingestion de documents + es: Ingestión de documentos + zh: 文档 ingest + - id: audit + title: + en: Dataset Audit + tr: Veri Seti Denetimi + de: Datensatz-Audit + fr: Audit de jeu de données + es: Auditoría de dataset + zh: 数据集审计 + - id: pii-masking + title: + en: PII Masking + tr: PII Maskeleme + de: PII-Maskierung + fr: Masquage des PII + es: Enmascaramiento PII + zh: PII 屏蔽 + - id: secrets + title: + en: Secrets Scrubbing + tr: Sırların Temizlenmesi + de: Secrets-Bereinigung + fr: Nettoyage des secrets + es: Limpieza de secretos + zh: Secrets 清洗 + - id: deduplication + title: + en: Deduplication + tr: Tekrar Tespiti + de: Deduplikation + fr: Déduplication + es: Deduplicación + zh: 去重 + - id: quality-filter + title: + en: Quality Filter + tr: Kalite Filtresi + de: Qualitätsfilter + fr: Filtre qualité + es: Filtro de calidad + zh: 质量过滤 + - id: language-detection + title: + en: Language Detection + tr: Dil Tespiti + de: Spracherkennung + fr: Détection de langue + es: Detección de idioma + zh: 语言识别 + - id: leakage + title: + en: Cross-Split Leakage + tr: Split-Arası Sızıntı + de: Split-übergreifender Leak + fr: Fuite inter-split + es: Fuga entre splits + zh: Split 间泄漏 + - id: synthetic-data + title: + en: Synthetic Data + tr: Sentetik Veri + de: Synthetische Daten + fr: Données synthétiques + es: Datos sintéticos + zh: 合成数据 + + - id: evaluation + icon: shield + title: + en: Evaluation & Safety + tr: Değerlendirme ve Güvenlik + de: Evaluierung & Sicherheit + fr: Évaluation et sécurité + es: Evaluación y seguridad + zh: 评估与安全 + pages: + - id: benchmarks + title: + en: Benchmark Integration + tr: Benchmark Entegrasyonu + de: Benchmark-Integration + fr: Intégration de benchmark + es: Integración de benchmark + zh: Benchmark 集成 + - id: judge + title: + en: LLM-as-Judge + tr: LLM-as-Judge + de: LLM-as-Judge + fr: LLM-as-judge + es: LLM-as-judge + zh: LLM-as-judge + - id: safety + title: + en: Llama Guard Safety + tr: Llama Guard Güvenliği + de: Llama-Guard-Sicherheit + fr: Sécurité Llama Guard + es: Seguridad Llama Guard + zh: Llama Guard 安全 + - id: auto-revert + title: + en: Auto-Revert + tr: Otomatik Geri Alma + de: Auto-Rollback + fr: Rollback automatique + es: Reversión automática + zh: 自动回滚 + - id: trend-tracking + title: + en: Trend Tracking + tr: Trend İzleme + de: Trend-Tracking + fr: Suivi de tendance + es: Seguimiento de tendencias + zh: 趋势跟踪 + + - id: compliance + icon: badge + title: + en: Compliance + tr: Uyumluluk + de: Compliance + fr: Conformité + es: Cumplimiento + zh: 合规 + pages: + - id: overview + title: + en: Overview + tr: Genel Bakış + de: Überblick + fr: Vue d'ensemble + es: Visión general + zh: 概览 + - id: annex-iv + title: { en: Annex IV, tr: Annex IV, de: Annex IV, fr: Annex IV, es: Annex IV, zh: Annex IV } + - id: audit-log + title: + en: Audit Log + tr: Audit Log + de: Audit-Log + fr: Log d'audit + es: Log de auditoría + zh: 审计日志 + - id: human-oversight + title: + en: Human Oversight + tr: İnsan Gözetimi + de: Menschliche Aufsicht + fr: Supervision humaine + es: Supervisión humana + zh: 人工监督 + - id: model-card + title: + en: Model Card + tr: Model Card + de: Model Card + fr: Model card + es: Model card + zh: Model card + - id: gdpr + title: + en: GDPR / KVKK + tr: KVKK / GDPR + de: DSGVO / KVKK + fr: RGPD / KVKK + es: RGPD / KVKK + zh: GDPR / KVKK + + - id: operations + icon: server + title: + en: Operations + tr: Operasyon + de: Betrieb + fr: Exploitation + es: Operaciones + zh: 运维 + pages: + - id: cicd + title: + en: CI/CD Pipelines + tr: CI/CD Hatları + de: CI/CD-Pipelines + fr: Pipelines CI/CD + es: Pipelines CI/CD + zh: CI/CD 流水线 + - id: webhooks + title: + en: Webhooks + tr: Webhook'lar + de: Webhooks + fr: Webhooks + es: Webhooks + zh: Webhook + - id: experiment-tracking + title: + en: Experiment Tracking + tr: Deney Takibi + de: Experiment-Tracking + fr: Suivi d'expériences + es: Seguimiento de experimentos + zh: 实验跟踪 + - id: air-gap + title: + en: Air-Gap Operation + tr: Air-Gap Operasyonu + de: Air-Gap-Betrieb + fr: Fonctionnement air-gap + es: Operación air-gap + zh: 气隙运行 + - id: docker + title: + en: Docker + tr: Docker + de: Docker + fr: Docker + es: Docker + zh: Docker + - id: gpu-cost + title: + en: GPU Cost Estimation + tr: GPU Maliyet Tahmini + de: GPU-Kostenschätzung + fr: Estimation du coût GPU + es: Estimación de coste GPU + zh: GPU 成本估算 + - id: vram-fit-check + title: + en: VRAM Fit-Check + tr: VRAM Fit-Check + de: VRAM-Fit-Check + fr: Vérification VRAM + es: Comprobación VRAM + zh: VRAM 适配检查 + - id: troubleshooting + title: + en: Troubleshooting + tr: Sorun Giderme + de: Fehlerbehebung + fr: Dépannage + es: Solución de problemas + zh: 故障排除 + + - id: deployment + icon: ship + title: + en: Deployment + tr: Deployment + de: Deployment + fr: Déploiement + es: Despliegue + zh: 部署 + pages: + - id: chat + title: + en: Interactive Chat + tr: İnteraktif Sohbet + de: Interaktiver Chat + fr: Chat interactif + es: Chat interactivo + zh: 交互式聊天 + - id: gguf-export + title: + en: GGUF Export + tr: GGUF Export + de: GGUF-Export + fr: Export GGUF + es: Export GGUF + zh: GGUF 导出 + - id: deploy-targets + title: + en: Deploy Targets + tr: Deploy Hedefleri + de: Deploy-Ziele + fr: Cibles de déploiement + es: Objetivos de despliegue + zh: 部署目标 + - id: model-merging + title: + en: Model Merging + tr: Model Birleştirme + de: Model-Merging + fr: Fusion de modèles + es: Fusión de modelos + zh: 模型合并 + + - id: reference + icon: book-open + title: + en: Reference + tr: Referans + de: Referenz + fr: Référence + es: Referencia + zh: 参考 + pages: + - id: configuration + title: + en: Configuration Reference + tr: Konfigürasyon Referansı + de: Konfigurationsreferenz + fr: Référence de configuration + es: Referencia de configuración + zh: 配置参考 + - id: cli + title: + en: CLI Reference + tr: CLI Referansı + de: CLI-Referenz + fr: Référence CLI + es: Referencia CLI + zh: CLI 参考 + - id: exit-codes + title: + en: Exit Codes + tr: Exit Kodları + de: Exit-Codes + fr: Codes de sortie + es: Códigos de salida + zh: 退出码 + - id: yaml-templates + title: + en: YAML Templates + tr: YAML Şablonları + de: YAML-Vorlagen + fr: Modèles YAML + es: Plantillas YAML + zh: YAML 模板 diff --git a/docs/usermanuals/en/compliance/annex-iv.md b/docs/usermanuals/en/compliance/annex-iv.md new file mode 100644 index 00000000..c229f0ce --- /dev/null +++ b/docs/usermanuals/en/compliance/annex-iv.md @@ -0,0 +1,164 @@ +--- +title: Annex IV +description: The EU AI Act Article 11 technical documentation, auto-populated from your training run. +--- + +# Annex IV + +Annex IV of the EU AI Act (Regulation (EU) 2024/1689) defines the eight-section technical documentation required for high-risk AI systems. ForgeLM produces this artifact automatically — `artifacts/annex_iv.json` after every run with `compliance.annex_iv: true`. + +## The eight sections + +| § | Section | What ForgeLM auto-populates | +|---|---|---| +| 1 | General description | Model name, intended purpose, geographies, version. | +| 2 | Detailed system description | Base model, trainer (SFT/DPO/...), dataset summary. | +| 3 | Monitoring | Eval thresholds, auto-revert triggers, trend tracking config. | +| 4 | Risk management | Risk classification, mitigations applied, residual risks. | +| 5 | Lifecycle | Training timestamp, dataset versions, source references. | +| 6 | Harmonised standards | Listed compliance frameworks (EU AI Act, GDPR, ISO 27001). | +| 7 | EU declaration of conformity | Scaffold; signed by a human as final step. | +| 8 | Post-market monitoring plan | Reference to deployment surveillance config. | + +## Configuration → Annex IV + +Most of Annex IV is filled from your `compliance:` YAML block. Required fields: + +```yaml +compliance: + annex_iv: true # master switch + + # Section 1: General description + intended_purpose: "Multilingual customer-support assistant for telecom" + deployment_geographies: ["TR", "EU"] + responsible_party: "Acme Corp " + version: "1.2.0" + + # Section 4: Risk classification + risk_classification: "high-risk" # or "minimal", "limited" + risk_assessment: + foreseeable_misuse: + - "Customer impersonation in social engineering attacks" + - "Generation of fraudulent invoices" + mitigations: + - "Llama Guard S5 (defamation) gate enforced" + - "PII masked at ingest" + residual_risks: + - "Adversarial jailbreaks against system prompt" + + # Section 6: Standards + standards: ["EU AI Act", "GDPR", "ISO 27001"] + + # Section 8: Post-market plan reference + post_market_plan: "https://internal.acme.example/forgelm-monitoring" +``` + +The audit step ([Dataset Audit](#/data/audit)) provides Section 2's dataset summary and Section 5's data lineage automatically. + +## Output structure + +`annex_iv.json` follows the EU AI Act schema closely: + +```json +{ + "schema_version": "annex_iv/1.0", + "section_1_general_description": { + "name": "Acme Customer Support v1.2.0", + "intended_purpose": "...", + "deployment_geographies": ["TR", "EU"], + "responsible_party": "Acme Corp ", + "version": "1.2.0" + }, + "section_2_detailed_system_description": { + "base_model": "Qwen/Qwen2.5-7B-Instruct", + "trainer": "dpo", + "datasets": [{ + "path": "data/preferences.jsonl", + "row_count": 12400, + "audit_report": "audit/data_audit_report.json", + "source_documents": "data/sources.json" + }], + "training_recipe": "configs/customer-support.yaml" + }, + "section_3_monitoring": { + "benchmark_floors": {"hellaswag": 0.55, "...": "..."}, + "safety_thresholds": {"S5": 0.30, "...": "..."}, + "trend_tracking": true + }, + "section_4_risk_management": { + "classification": "high-risk", + "foreseeable_misuse": [...], + "mitigations": [...], + "residual_risks": [...] + }, + "section_5_lifecycle": { + "trained_at": "2026-04-29T14:01:32Z", + "training_duration_seconds": 1892, + "config_hash": "sha256:deadbeef...", + "dataset_hashes": {...} + }, + "section_6_harmonised_standards": ["EU AI Act", "GDPR", "ISO 27001"], + "section_7_declaration_of_conformity": { + "status": "scaffold", + "signed_by": null, + "signed_at": null, + "notes": "Requires human review and signature before submission." + }, + "section_8_post_market_plan": "https://internal.acme.example/forgelm-monitoring", + "manifest_sha256": "..." +} +``` + +## Tamper-evidence + +`annex_iv.json` is itself hashed in `manifest.json`, alongside every other artifact in the bundle. The manifest is the canonical pointer to the immutable bundle: + +```json +{ + "schema": "manifest/1.0", + "artifacts": { + "annex_iv.json": "sha256:abc123...", + "audit_log.jsonl": "sha256:def456...", + "data_audit_report.json": "sha256:789abc...", + "safety_report.json": "sha256:fedcba...", + "benchmark_results.json": "sha256:111222..." + }, + "generated_at": "2026-04-29T14:33:04Z" +} +``` + +For real tamper-evidence, ship `manifest.json` to a separate write-once store (S3 Object Lock, HSM-signed ledger, etc.). The toolkit produces the artefact; the operational chain-of-custody is your responsibility. + +## Validating Annex IV + +Before treating an Annex IV as "audit-ready", verify the schema: + +```shell +$ forgelm verify-annex-iv checkpoints/run/artifacts/annex_iv.json +✓ schema valid +✓ all required fields present +✓ manifest checksums match +⚠ section_7 declaration unsigned (expected for new runs) +``` + +The `forgelm verify-annex-iv` command also re-computes manifest hashes and checks for tampering since generation. + +## Common pitfalls + +:::warn +**Skipping the human review step on Section 7.** The declaration of conformity is a legal document. The auto-generated scaffold is not signed and has no legal effect — a human must review and sign before submission. +::: + +:::warn +**Treating ForgeLM's output as a certification.** ForgeLM produces evidence; certification is a notified-body activity. The terminology in our docs reflects this: "Annex-IV-style artifact", "scaffold", "evidence bundle" — never "certified". +::: + +:::tip +For high-risk deployments, version the Annex IV artifact alongside model versions in your model registry. Auditors expect to see Annex IV per release, not per training run. +::: + +## See also + +- [Compliance Overview](#/compliance/overview) — context for the rest of the bundle. +- [Audit Log](#/compliance/audit-log) — append-only event log. +- [Human Oversight](#/compliance/human-oversight) — Article 14. diff --git a/docs/usermanuals/en/compliance/audit-log.md b/docs/usermanuals/en/compliance/audit-log.md new file mode 100644 index 00000000..461b18a9 --- /dev/null +++ b/docs/usermanuals/en/compliance/audit-log.md @@ -0,0 +1,142 @@ +--- +title: Audit Log +description: Append-only event log over training, evaluation, and revert decisions — Article 12. +--- + +# Audit Log + +EU AI Act Article 12 requires high-risk AI systems to maintain logs of operationally relevant events. ForgeLM's `audit_log.jsonl` is an append-only, SHA-256-anchored sequence of events covering training start, evaluation gates, auto-revert decisions, and model export. + +## Format + +One JSON object per line: + +```jsonl +{"ts":"2026-04-29T14:01:32Z","seq":1,"event":"run_start","run_id":"abc123","config_hash":"sha256:dead..."} +{"ts":"2026-04-29T14:01:35Z","seq":2,"event":"data_audit_complete","verdict":"clean","..."} +{"ts":"2026-04-29T14:18:55Z","seq":3,"event":"training_epoch_complete","epoch":1,"loss":1.42} +{"ts":"2026-04-29T14:33:04Z","seq":4,"event":"benchmark_complete","verdict":"pass"} +{"ts":"2026-04-29T14:33:08Z","seq":5,"event":"safety_eval_complete","verdict":"pass"} +{"ts":"2026-04-29T14:33:10Z","seq":6,"event":"run_complete","exit_code":0,"prev_hash":"sha256:beef..."} +``` + +Every entry has: +- **`ts`** — ISO-8601 UTC timestamp. +- **`seq`** — monotonic sequence number within the run (resets per-run). +- **`event`** — event type (see below). +- **`prev_hash`** — SHA-256 of the previous entry (chained for tamper-evidence). +- Event-specific fields. + +## Event types + +| Event | When emitted | +|---|---| +| `run_start` | At the start of every `forgelm` invocation. | +| `config_validated` | After `--dry-run` passes. | +| `data_audit_complete` | After `forgelm audit` runs (whether ad hoc or as part of a training run). | +| `training_epoch_complete` | After each training epoch. | +| `training_step_milestone` | At configurable step intervals (default 1000). | +| `benchmark_complete` | After the benchmark suite runs. | +| `safety_eval_complete` | After Llama Guard scoring. | +| `auto_revert` | When auto-revert triggers. | +| `human_approval_request` | When `compliance.human_approval` blocks. | +| `human_approval_granted` | When approval is signed. | +| `model_exported` | After `forgelm export` writes a deployable artefact. | +| `run_complete` | At successful exit. | +| `run_failed` | At non-zero exit. | + +## Append-only by design + +ForgeLM never rewrites prior log entries. New events go at the end. The chained `prev_hash` makes any modification detectable: if you change entry N, every entry from N+1 onwards has wrong `prev_hash` references. + +:::warn +**Convention, not enforcement.** The toolkit writes append-only and hashes the chain, but the file lives on your filesystem — anyone with write access can edit it. For real tamper-evidence, ship the log to a separate write-once store (S3 Object Lock, ledger DB, HSM). This is your operational responsibility. +::: + +## Verifying integrity + +```shell +$ forgelm verify-log checkpoints/run/artifacts/audit_log.jsonl +✓ 87 entries, all timestamps monotonic +✓ all prev_hash chains valid +✓ no gaps in seq numbers +``` + +If `verify-log` reports a chain break, the log was modified after generation. Investigate before treating it as evidence. + +## Per-run vs per-project + +Each training run produces its own `audit_log.jsonl` in that run's `artifacts/` directory. For per-project history, ForgeLM also maintains `.forgelm/global-audit-log.jsonl` at the project root (gitignored by default — opt in to commit). + +The global log records *cross-run* events: + +- `run_start` and `run_complete` for every run in the project. +- Manual model promotions and rollbacks. +- Configuration changes (when `forgelm` detects new YAML versions). + +## Configuration + +```yaml +compliance: + audit_log: + enabled: true + path: "${output.dir}/artifacts/audit_log.jsonl" + step_milestone_interval: 1000 # log step events every N steps + include_config_dump: true # emit full config in run_start event + redact_secrets: true # mask api keys in dumped config +``` + +## Forwarding to external stores + +For tamper-evidence in production, forward log entries to a separate write-once or append-only store: + +```yaml +compliance: + audit_log: + forward_to: + - type: "s3" + bucket: "compliance-audit-logs" + prefix: "forgelm/{run_id}/" + object_lock: true + - type: "syslog" + host: "audit.internal:514" + protocol: "tcp" +``` + +ForgeLM mirrors every emitted event to the configured destinations. If the external store is unreachable, the run fails (don't silently drop audit events). + +## Reading the log + +For human review: + +```shell +$ jq -r '.event + "\t" + .ts' checkpoints/run/artifacts/audit_log.jsonl +run_start 2026-04-29T14:01:32Z +config_validated 2026-04-29T14:01:33Z +data_audit_complete 2026-04-29T14:01:35Z +training_epoch_complete 2026-04-29T14:18:55Z +... +run_complete 2026-04-29T14:33:10Z +``` + +For dashboards, the JSONL flows naturally into Loki, OpenSearch, or any log-aggregation tool. + +## Common pitfalls + +:::warn +**Editing the log "to fix a typo".** Don't. Even cosmetic edits break the chain hash and undermine the audit value. If you genuinely need to amend information, append a new event of type `correction` with a `corrects_seq` reference. +::: + +:::warn +**Storing the log only on training-host disks.** A failed disk = lost audit evidence. Always forward to durable storage (S3 with versioning + Object Lock, ledger DB). +::: + +:::tip +**Chain logs across runs in production.** When promoting a checkpoint to production, append a `model_promoted` event referencing the previous version. Auditors love a continuous chain of custody from training to deployment. +::: + +## See also + +- [Annex IV](#/compliance/annex-iv) — the technical doc that points at the audit log. +- [Auto-Revert](#/evaluation/auto-revert) — produces the `auto_revert` events. +- [Human Oversight](#/compliance/human-oversight) — produces the approval events. diff --git a/docs/usermanuals/en/compliance/gdpr.md b/docs/usermanuals/en/compliance/gdpr.md new file mode 100644 index 00000000..f2059b66 --- /dev/null +++ b/docs/usermanuals/en/compliance/gdpr.md @@ -0,0 +1,151 @@ +--- +title: GDPR / KVKK +description: Data protection compliance — PII minimisation, data subject rights, and audit evidence. +--- + +# GDPR / KVKK + +GDPR (Europe) and KVKK (Türkiye) impose data protection requirements on personal data used in training. ForgeLM's role: prevent personal data from entering training in the first place, document what gets ingested, and produce evidence for data subject requests. + +## What GDPR / KVKK require for training data + +| Principle | Article | What it means for training | +|---|---|---| +| **Lawfulness** | GDPR Art. 5(1)(a) | You must have a lawful basis for processing personal data. | +| **Purpose limitation** | GDPR Art. 5(1)(b) | Data collected for purpose A can't be used for unrelated purpose B. | +| **Data minimisation** | GDPR Art. 5(1)(c) | Don't collect or retain personal data beyond what's necessary. | +| **Accuracy** | GDPR Art. 5(1)(d) | Keep data accurate; correct or erase incorrect data. | +| **Storage limitation** | GDPR Art. 5(1)(e) | Don't retain longer than necessary. | +| **Integrity & confidentiality** | GDPR Art. 5(1)(f) | Protect against unauthorised access. | +| **Accountability** | GDPR Art. 5(2) | You must be able to demonstrate compliance. | + +KVKK (Türkiye) mirrors these principles closely. + +## How ForgeLM addresses each + +### Data minimisation (Art. 5(1)(c)) + +PII masking at ingest replaces personal identifiers with placeholders: + +```yaml +ingestion: + pii_mask: + enabled: true + locale: "tr" + categories: ["email", "phone", "iban", "id_tr"] +``` + +By the time data lands in JSONL, identifiable subjects are removed. See [PII Masking](#/data/pii-masking). + +### Accountability (Art. 5(2)) + +Every audit produces `data_audit_report.json` documenting: + +- Detected PII categories and counts (before masking). +- Source attribution (which document each row came from). +- Quality and language distribution. +- SHA-256 manifest for tamper-evidence. + +These reports flow into the Annex IV bundle. When a regulator asks "what personal data was in your training set?", you have a structured answer. + +### Storage limitation (Art. 5(1)(e)) + +ForgeLM doesn't retain raw user data — it produces JSONL artifacts you control. For automated retention enforcement: + +```yaml +ingestion: + retention: + raw_documents: + ttl_days: 90 # auto-delete originals after N days + audit_reports: + ttl_days: 365 +``` + +(The actual deletion is your storage layer's responsibility; ForgeLM just records the intended TTL in the audit log.) + +## Data subject requests + +Most-common request types and how ForgeLM helps: + +### Right of access (Art. 15) + +"What personal data do you hold about me?" + +Run reverse-PII on your training data: + +```shell +$ forgelm reverse-pii --query "ali@example.com" data/*.jsonl +No matches found in masked data. +``` + +Because PII was masked at ingest, no specific person's data is recoverable from the model. The audit report confirms this. + +### Right to erasure (Art. 17) + +"Delete my data." + +If a person's data was in your training set: +1. The masked JSONL doesn't contain their identifying info — already minimised. +2. Source documents may still — drop them from your raw store and re-ingest if necessary. +3. The model may have memorised some details — see "model-level erasure" below. + +### Model-level erasure + +LLMs can memorise rare strings from training. Even with PII masking, removing all traces from a deployed model is hard. ForgeLM's defences: + +- **Prevent memorisation:** PII masking, deduplication (memorised data is usually duplicated data). +- **Detect memorisation:** the audit step flags rows that overlap with known PII patterns. +- **Re-train as last resort:** if a specific subject's data leaked despite masking, re-train without that source. + +For zero-tolerance scenarios (medical, legal), pair PII masking with manual review before training. + +## DPIA (Data Protection Impact Assessment) + +For high-risk processing, GDPR Art. 35 requires a DPIA. ForgeLM doesn't write your DPIA, but the audit bundle provides input data: + +- Risk classification → from `compliance.risk_classification`. +- Personal data inventory → from `data_audit_report.json`. +- Mitigations applied → from `compliance.risk_assessment.mitigations`. +- Residual risks → from `compliance.risk_assessment.residual_risks`. + +A DPIA template that consumes these is in `docs/qms/dpia-template.md`. + +## Configuration reference + +```yaml +compliance: + data_protection: + framework: "GDPR" # GDPR | KVKK | both + lawful_basis: "legitimate-interest" # consent | contract | legal-obligation | ... + purpose: "Customer-support assistant for X" + data_controller: "Acme Corp" + data_subjects: "telecom customers" + retention_basis: "model lifecycle (~3 years) plus audit period" + international_transfers: + enabled: false # set true if training data crosses borders + safeguards: "Standard Contractual Clauses 2021/914" +``` + +## Common pitfalls + +:::warn +**Treating PII masking as DPIA-replacement.** Masking is a technical mitigation, not a legal assessment. A DPIA is a documented analysis of risks, mitigations, and residual harm — required separately for high-risk processing. +::: + +:::warn +**Skipping data audit on internal data.** Internal data is the most common source of inadvertent personal data exposure (employee records leaking into customer-support training). Audit everything. +::: + +:::warn +**International transfers.** If your training data crosses jurisdiction boundaries (Turkish data trained in EU, EU data trained in US), additional safeguards apply. Set `international_transfers.enabled: true` and document the safeguards. +::: + +:::tip +For sectors like health and finance, consult a privacy specialist *before* the first training run. ForgeLM's defaults are sensible but they don't replace sector-specific legal review. +::: + +## See also + +- [PII Masking](#/data/pii-masking) — the technical implementation. +- [Compliance Overview](#/compliance/overview) — broader context. +- [Annex IV](#/compliance/annex-iv) — packaged compliance evidence. diff --git a/docs/usermanuals/en/compliance/human-oversight.md b/docs/usermanuals/en/compliance/human-oversight.md new file mode 100644 index 00000000..03052f15 --- /dev/null +++ b/docs/usermanuals/en/compliance/human-oversight.md @@ -0,0 +1,164 @@ +--- +title: Human Oversight +description: Block model promotion until a human reviews and signs off — Article 14 gate. +--- + +# Human Oversight + +EU AI Act Article 14 requires high-risk AI systems to provide for human oversight. ForgeLM implements this as an optional config gate: when `compliance.human_approval: true`, model promotion blocks until a human signs an approval. + +## How the gate works + +```mermaid +sequenceDiagram + participant Train as forgelm + participant Eval as Eval pipeline + participant Approver as Human approver + participant Audit as Audit log + participant Output as Output dir + + Train->>Eval: Training complete, run eval + Eval->>Eval: Benchmarks + safety pass + Eval->>Audit: Append "human_approval_request" + Eval->>Approver: Webhook + structured request + Approver-->>Eval: Sign approval (CLI / webhook callback) + Eval->>Audit: Append "human_approval_granted" with signature + Eval->>Output: Promote checkpoint +``` + +Without the human signature, the checkpoint stays in a "pending" state and the run exits with code 4 (waiting). It's *not* a failure — it's a controlled hold for review. + +## Configuration + +```yaml +compliance: + human_approval: true + approval: + request_webhook: "${SLACK_WEBHOOK}" # optional notification + signature_method: "cli" # cli | webhook | api + timeout_hours: 48 # auto-fail after this + require_role: "ml-compliance-lead" # who can approve + quorum: 1 # required approvers +``` + +## Signature methods + +### CLI (default) + +The trainer halts after eval and prints: + +```text +[2026-04-29 14:33:10] Human approval required. + Run ID: abc123 + Bundle: checkpoints/run/artifacts/ + + To approve: forgelm approve --run-id abc123 --reviewer "Cemil " + To reject: forgelm approve --run-id abc123 --reject --reason "..." +``` + +The reviewer runs the approval command from any machine with access to the artifacts directory. ForgeLM verifies their identity via SSH key signing or env-set token, signs the audit log, and resumes promotion. + +### Webhook callback + +For integration with internal approval systems: + +```yaml +approval: + signature_method: "webhook" + webhook_url: "https://internal.example/approvals/{run_id}/decide" +``` + +The trainer halts and posts the artifact bundle to your webhook. Your system handles the human review and POSTs back to ForgeLM's resume endpoint with a signed JWT. + +### API + +For self-service automation (e.g. a "promote this run" button in your dashboard): + +```yaml +approval: + signature_method: "api" + resume_token: "${FORGELM_RESUME_TOKEN}" +``` + +Your dashboard calls ForgeLM's resume endpoint directly with the run ID and reviewer identity. Signatures are recorded in the audit log. + +## What's in an approval signature + +Every approval (or rejection) appends to `audit_log.jsonl`: + +```json +{ + "ts": "2026-04-29T15:18:42Z", + "seq": 87, + "event": "human_approval_granted", + "run_id": "abc123", + "reviewer": "Cemil Ilik ", + "role": "ml-compliance-lead", + "method": "cli", + "signature": "ed25519:...", + "comment": "Reviewed safety report; S5 max 0.04 acceptable for this deployment.", + "artifact_hash": "sha256:..." +} +``` + +The `signature` is over the artifact bundle's `manifest.json` hash — it certifies the reviewer saw *exactly* what was produced. + +## Quorum (multi-reviewer) + +For high-risk deployments, require multiple approvers: + +```yaml +approval: + quorum: 2 + require_role: "ml-compliance-lead" +``` + +Each approver runs the CLI command independently. Promotion happens after the quorum signs (or one of them rejects). + +## Timeouts + +After `timeout_hours`, an unsigned run auto-fails with exit code 4 + a structured event: + +```json +{"event": "human_approval_timeout", "expired_at": "2026-04-30T14:33:10Z"} +``` + +Default is 48 hours. Set to 0 for "no timeout — wait forever" (not recommended in CI). + +## Inspecting pending runs + +```shell +$ forgelm approvals --pending +RUN_ID REQUESTED_AT ARTIFACTS EXPIRES +abc123 2026-04-29T14:33Z checkpoints/run/artifacts/ in 47h +def456 2026-04-29T09:12Z checkpoints/sft-only/artifacts/ in 42h +``` + +```shell +$ forgelm approvals --show abc123 +... full artifact summary including audit, benchmarks, safety, model card ... +``` + +## Common pitfalls + +:::warn +**Auto-approving in CI to "unblock the pipeline".** Defeats the purpose of human oversight. If the gate is in your way, you're either over-using it (turn it off for non-high-risk runs) or under-staffing reviewers. +::: + +:::warn +**Reviewer rubber-stamping.** A signature must be informed. Display the full artifact summary in the approval flow so the reviewer actually sees what they're signing for. +::: + +:::warn +**No quorum for shipping decisions.** For high-risk production deployments, single-reviewer approval is insufficient. Always require quorum >= 2. +::: + +:::tip +**Make the approval CLI accessible.** Reviewers shouldn't need to SSH into the training host to approve. Set up the artifacts directory on shared storage so reviewers can run `forgelm approve` from their own machines. +::: + +## See also + +- [Audit Log](#/compliance/audit-log) — where signatures are recorded. +- [Annex IV](#/compliance/annex-iv) — Section 7 declaration is signed by humans, not the toolkit. +- [Webhooks](#/operations/webhooks) — approval requests can fire Slack/Teams alerts. diff --git a/docs/usermanuals/en/compliance/model-card.md b/docs/usermanuals/en/compliance/model-card.md new file mode 100644 index 00000000..9fa22644 --- /dev/null +++ b/docs/usermanuals/en/compliance/model-card.md @@ -0,0 +1,159 @@ +--- +title: Model Card +description: Auto-generated transparency documentation — Article 13. +--- + +# Model Card + +EU AI Act Article 13 requires transparency: deployed AI systems must be accompanied by clear documentation of capabilities, limitations, intended use, and training data. ForgeLM generates a HuggingFace-compatible `README.md` model card after every successful run. + +## What ForgeLM auto-populates + +| Section | Source | +|---|---| +| **Model details** | `model.name_or_path`, training paradigm, version. | +| **Intended use** | `compliance.intended_purpose`. | +| **Out-of-scope use** | `compliance.risk_assessment.foreseeable_misuse`. | +| **Training data** | Audit summaries from each `datasets:` entry. | +| **Training procedure** | YAML config snapshot. | +| **Evaluation** | `benchmark_results.json` summary. | +| **Safety** | `safety_report.json` summary. | +| **Limitations** | `compliance.risk_assessment.residual_risks`. | +| **Citation** | Cites teacher model if synthetic data was used. | +| **License** | From `compliance.license` field. | + +The output is a Markdown file at `checkpoints/run/README.md` ready to upload to HuggingFace Hub. + +## Sample output + +```markdown +# Acme Customer Support v1.2.0 + +Customer-support assistant fine-tuned from Qwen2.5-7B-Instruct using ForgeLM 0.5.2. + +## Model details + +- **Base model:** Qwen/Qwen2.5-7B-Instruct +- **Fine-tuning paradigm:** SFT → DPO +- **Parameter-efficient method:** QLoRA (rank 16, alpha 32, DoRA enabled) +- **Trained:** 2026-04-29 +- **Languages:** Turkish, English +- **License:** Apache 2.0 + +## Intended use + +Multilingual customer-support assistant for telecom. Deployed within +authenticated user sessions to answer billing, plan, and technical +support questions. + +## Out-of-scope use + +This model is **not** intended for: +- Customer impersonation in social engineering attacks. +- Generation of fraudulent invoices. +- Use outside Turkish/English language pairs. +- Use without authentication or rate limiting. + +## Training data + +- 12,400 preference rows (`data/preferences.jsonl`) + - Audit verdict: warnings (12 PII medium-severity flags, masked at ingest) + - Cross-split overlap: 0 + - Language distribution: 99.2% TR, 0.5% EN + +## Training procedure + +Full configuration in `config_snapshot.yaml`. Highlights: + +- Trainer: `dpo` +- Beta: 0.1 +- Learning rate: 5e-6 +- Epochs: 1 +- Batch size: 2 (effective 32 with accumulation) + +## Evaluation + +| Task | Score | Floor | Verdict | +|---|---|---|---| +| hellaswag | 0.617 | 0.55 | pass | +| truthfulqa | 0.482 | 0.45 | pass | +| arc_easy | 0.74 | 0.70 | pass | + +## Safety + +Llama Guard 3 8B scoring across S1–S14: + +- All blocked categories (S1, S2, S5, S10) within 0.05 of pre-train baseline. +- No category at high severity. + +Full report in `artifacts/safety_report.json`. + +## Limitations + +- Adversarial jailbreaks against system prompt may occasionally succeed. +- Performance degrades on dialogue turns longer than 4096 tokens. +- Model was trained on Turkish-English bilingual data only — no support + for other languages. + +## Compliance + +- EU AI Act: Annex IV technical documentation in `artifacts/annex_iv.json` +- GDPR: PII masked at ingest; no training data retains identifiable subjects +- Audit log: `artifacts/audit_log.jsonl` + +For commercial use, see `LICENSE`. + +## Citation + +If you use this model, please cite: + +``` +@misc{acme2026, + title = {Acme Customer Support v1.2.0}, + author = {Acme Corp}, + year = {2026}, + note = {Fine-tuned with ForgeLM 0.5.2} +} +``` +``` + +## Configuration + +```yaml +output: + model_card: true # default + model_card_template: null # custom Jinja2 template path +``` + +For custom branding, override the default template: + +```yaml +output: + model_card_template: "templates/acme-card.j2" +``` + +The template gets the same data as the default — just renders differently. + +## Manual additions + +The default model card covers what ForgeLM can auto-determine. For manual additions (acknowledgements, custom warnings), append a `## Notes` section to the generated `README.md` after the run. The audit log treats this as a `model_card_amended` event. + +## Common pitfalls + +:::warn +**Stale model cards from previous runs.** Each run overwrites `README.md`. If you've manually edited the previous version, those edits are lost. For amendments that should persist across runs, add them to the `compliance.notes` YAML field instead. +::: + +:::warn +**Forgetting `compliance.license`.** Without it, the auto-generated card shows "License: not specified", which fails most internal review processes. Set the license explicitly. +::: + +:::tip +For HuggingFace Hub publication, ForgeLM's model card uses HuggingFace's standard front-matter format — `language:`, `license:`, `tags:` etc. — so it renders correctly on the Hub UI. +::: + +## See also + +- [Annex IV](#/compliance/annex-iv) — the Article 11 sibling. +- [Compliance Overview](#/compliance/overview) — context. +- [Configuration Reference](#/reference/configuration) — `output.model_card` field. diff --git a/docs/usermanuals/en/compliance/overview.md b/docs/usermanuals/en/compliance/overview.md new file mode 100644 index 00000000..c675fd80 --- /dev/null +++ b/docs/usermanuals/en/compliance/overview.md @@ -0,0 +1,126 @@ +--- +title: Compliance Overview +description: How ForgeLM maps EU AI Act, GDPR, and ISO 27001 requirements onto its training pipeline. +--- + +# Compliance Overview + +ForgeLM was built for teams that have to defend their training pipeline to a regulator, not just a CTO. Every successful (or failed) run produces a structured evidence bundle that maps cleanly onto EU AI Act Articles 9-17, GDPR Article 5, and ISO 27001 control objectives. + +```mermaid +flowchart TD + Run[Training run] --> Audit[Data audit] + Run --> Train[Train + checkpoints] + Run --> Eval[Eval + safety] + Run --> Doc[Auto model card] + + Audit --> A10[Article 10
Data governance] + Train --> A12[Article 12
Audit log] + Eval --> A9[Article 9
Risk management] + Eval --> A15[Article 15
Accuracy/robustness] + Doc --> A13[Article 13
Transparency] + Audit --> A11[Article 11
Annex IV bundle] + Train --> A11 + Eval --> A11 + + classDef artifact fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef article fill:#161a24,stroke:#f97316,color:#e6e7ec + classDef start fill:#1c2030,stroke:#22c55e,color:#e6e7ec + class Run start + class Audit,Train,Eval,Doc artifact + class A9,A10,A11,A12,A13,A15 article +``` + +## What gets produced + +Every run that has `compliance.annex_iv: true` produces an artifacts directory: + +```text +checkpoints/run/artifacts/ +├── annex_iv.json ← Article 11 — technical documentation +├── audit_log.jsonl ← Article 12 — append-only event log +├── data_audit_report.json ← Article 10 — data governance evidence +├── safety_report.json ← Article 9 + 15 — risk + safety assessment +├── benchmark_results.json ← Article 15 — accuracy +├── conformity_declaration.md ← Article 16 — declaration scaffold +└── manifest.json ← SHA-256 over every artifact above +``` + +This bundle is the deliverable for compliance reviews. Every file is hashed in `manifest.json` for tamper-evidence. + +## Articles ForgeLM addresses + +| Article | Topic | How ForgeLM addresses it | +|---|---|---| +| **9** | Risk management | Auto-revert + threshold gates + trend tracking. | +| **10** | Data governance | `forgelm audit` produces governance evidence per dataset. | +| **11** | Technical documentation | `annex_iv.json` is a populated Annex IV. | +| **12** | Record-keeping | Append-only `audit_log.jsonl` covering training start, eval gates, revert decisions. | +| **13** | Transparency | Auto-generated model card listing capabilities, limitations, training summary. | +| **14** | Human oversight | Optional `compliance.human_approval: true` blocks promotion until a human signs off. | +| **15** | Accuracy & robustness | Benchmark gates + safety eval + cybersecurity (PII / secrets at ingest). | +| **16-17** | Conformity & QMS | Declaration scaffold + QMS SOPs in `docs/qms/`. | + +For the full mapping with code references, see the [Compliance page on the public site](compliance.html). + +## What ForgeLM doesn't claim + +:::warn +ForgeLM **generates** Annex IV-style technical documentation. It does **not** certify your system as a high-risk AI system under the AI Act — that's a notified-body or self-assessment activity, outside any toolkit's scope. + +The audit log is append-only by convention and SHA-256-anchored. Real tamper-evidence requires shipping the log to a separate write-once store (S3 Object Lock, ledger DB). The toolkit produces the artefact; chain-of-custody is your operational responsibility. + +The PII/secrets regex sets are conservative by design — they prefer false-negatives over false-positives. For high-stakes corpora, pair with manual review before training. +::: + +## Enabling compliance artifacts + +Set in your YAML: + +```yaml +compliance: + annex_iv: true + data_audit_artifact: "./audit/data_audit_report.json" + human_approval: true # optional Article 14 gate + intended_purpose: "Customer-support assistant for Turkish telecom" + risk_classification: "high-risk" # or "minimal", "limited", etc. + deployment_geographies: ["TR", "EU"] + responsible_party: "Acme Corp " +``` + +Every field from `compliance:` flows into `annex_iv.json`. Required fields are validated at config load — a missing `intended_purpose` fails `--dry-run`. + +## What goes into Annex IV + +The Annex IV artifact has eight sections, all populated automatically: + +1. **General description** — model name, intended purpose, deployment geography. +2. **Detailed system description** — base model, training paradigm, dataset summary. +3. **Monitoring** — eval thresholds, auto-revert triggers, trend tracking. +4. **Risk management** — risk classification, mitigations, residual risks. +5. **Lifecycle** — training date, version, references to source data. +6. **Standards** — listed compliance frameworks (EU AI Act, GDPR, ISO 27001). +7. **Declaration of conformity** — scaffold; final declaration requires human signature. +8. **Post-market monitoring plan** — pointer to the deployed surveillance config. + +See [Annex IV](#/compliance/annex-iv) for the full schema. + +## Operational responsibilities (you, not ForgeLM) + +The toolkit produces evidence; the people produce certification. Your team is responsible for: + +- Reviewing the audit bundle after every run that's bound for production. +- Shipping the audit log to a write-once store for tamper-evidence. +- Conducting the conformity assessment with a notified body where required. +- Maintaining post-market monitoring once the model is deployed. +- Handling data subject requests (GDPR Articles 15-22). + +ForgeLM's QMS SOPs in `docs/qms/` cover the operational side — release process, incident response, data-source onboarding. + +## See also + +- [Annex IV](#/compliance/annex-iv) — full Article 11 artifact spec. +- [Audit Log](#/compliance/audit-log) — Article 12 event log. +- [Human Oversight](#/compliance/human-oversight) — Article 14 gate. +- [Model Card](#/compliance/model-card) — Article 13 transparency. +- [GDPR / KVKK](#/compliance/gdpr) — data protection. diff --git a/docs/usermanuals/en/concepts/alignment-overview.md b/docs/usermanuals/en/concepts/alignment-overview.md new file mode 100644 index 00000000..844d8689 --- /dev/null +++ b/docs/usermanuals/en/concepts/alignment-overview.md @@ -0,0 +1,121 @@ +--- +title: The Alignment Stack +description: How SFT, DPO, SimPO, KTO, ORPO, and GRPO fit together — and when to use which. +--- + +# The Alignment Stack + +Modern LLM fine-tuning is no longer a single algorithm — it's a *stack* of post-training paradigms, each addressing a different problem. ForgeLM gives you all six behind one declarative interface so you can pick the right tool without rewriting your pipeline. + +```mermaid +flowchart TD + Base[Base model
e.g. Qwen 2.5 / Llama 3] + SFT[SFT
format & content] + DPO[DPO
preference alignment] + SimPO[SimPO
preference, ref-free] + KTO[KTO
binary feedback] + ORPO[ORPO
SFT+DPO combined] + GRPO[GRPO
reasoning RL] + Out[Production-ready
aligned model] + + Base --> SFT + Base --> ORPO + Base --> GRPO + SFT --> DPO + SFT --> SimPO + SFT --> KTO + DPO --> Out + SimPO --> Out + KTO --> Out + ORPO --> Out + GRPO --> Out + + classDef base fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef sft fill:#161a24,stroke:#22c55e,color:#e6e7ec + classDef pref fill:#161a24,stroke:#f97316,color:#e6e7ec + classDef done fill:#1c2030,stroke:#fb923c,color:#e6e7ec + class Base base + class SFT,ORPO,GRPO sft + class DPO,SimPO,KTO pref + class Out done +``` + +## The three problems alignment solves + +### Problem 1: Format + +A base model can complete text but doesn't follow instructions, doesn't use chat turns, doesn't keep a system prompt, and doesn't know when to stop. **SFT** solves this: train on examples of the format you want. + +### Problem 2: Preferences + +After SFT, the model produces well-formatted outputs but quality varies — sometimes confident, sometimes evasive, sometimes verbose. **DPO**, **SimPO**, **KTO**, and **ORPO** all align the model towards preferred outputs. + +The differences: +- **DPO** — learns from `(chosen, rejected)` pairs against a reference model. Best-studied, most stable. +- **SimPO** — same as DPO but skips the reference model. Lower memory, slightly less stable. +- **KTO** — learns from binary `(prompt, response, good?)` signals. Use when you only have thumbs-up/down feedback. +- **ORPO** — combines SFT and preference loss in a single pass. Faster wall-clock; less flexible than separate stages. + +### Problem 3: Reasoning + +Some tasks (math, code, multi-step logic) benefit from reinforcement learning over reasoning traces, not just pairwise preferences. **GRPO** trains the model to maximise a reward function on its own outputs, with format and length shaping rewards built in. + +## A typical production sequence + +```mermaid +sequenceDiagram + participant Base as Base model + participant SFT as SFT stage + participant DPO as DPO stage + participant Eval as Eval & safety + participant Prod as Production + + Base->>SFT: 12K instruction pairs + SFT->>DPO: SFT checkpoint (helpful-but-bland) + DPO->>Eval: 3K preference pairs + Eval->>Eval: lm-eval-harness + Llama Guard + Eval->>Prod: Pass thresholds → promote + Eval->>SFT: Regression → auto-revert +``` + +Most teams reach production in two stages: SFT to teach format and content, then DPO/SimPO/KTO to sharpen preferences. ORPO collapses both into one stage when you need wall-clock speed and have both kinds of data ready. + +## Trade-offs at a glance + +| Stage | Data needed | Memory | Stability | When to skip | +|---|---|---|---|---| +| SFT | Prompt-completion pairs | 1× | Stable | Never — almost always needed | +| DPO | Chosen-rejected pairs | 2× | Stable | If you don't have preference data | +| SimPO | Chosen-rejected pairs | 1.2× | Moderate | If you have spare VRAM, prefer DPO | +| KTO | Binary thumbs-up/down | 1.5× | Moderate | If you have paired preferences (use DPO) | +| ORPO | Both pairs and preferences | 1.5× | Stable | If you want SFT and DPO as separate experiments | +| GRPO | Reward function or reward model | 2-3× | Tricky | Non-reasoning tasks | + +:::tip +**Don't skip SFT.** Even if you have great preference data, SFT first to teach format, then align with DPO/SimPO/KTO. Skipping SFT and going straight to DPO usually produces an unstable, format-broken model. +::: + +## Parameter-efficient methods + +All trainers above can be combined with parameter-efficient methods so they fit on commodity GPUs: + +- **LoRA / QLoRA / DoRA / PiSSA / rsLoRA** — train low-rank adapters instead of all weights. ~1% trainable parameters, ~10% VRAM, comparable quality on most tasks. +- **GaLore** — gradient projection, full-parameter training in LoRA-level memory. + +See [LoRA, QLoRA, DoRA](#/training/lora) and [GaLore](#/training/galore). + +## Distributed training + +Once your model is bigger than a single GPU's memory, ForgeLM supports: + +- **DeepSpeed ZeRO-2 / ZeRO-3** — shard optimiser states / gradients / parameters across GPUs. +- **FSDP** — PyTorch-native fully-sharded data parallelism. +- **Unsloth** — backend that's 2-5× faster on supported architectures (single-GPU only). + +See [Distributed Training](#/training/distributed). + +## Where to go next + +- [Choosing a Trainer](#/concepts/choosing-trainer) — a decision tree for picking among SFT/DPO/SimPO/KTO/ORPO/GRPO. +- [SFT](#/training/sft) — start here for almost any project. +- [Dataset Formats](#/concepts/data-formats) — what each trainer expects in JSONL. diff --git a/docs/usermanuals/en/concepts/choosing-trainer.md b/docs/usermanuals/en/concepts/choosing-trainer.md new file mode 100644 index 00000000..08e4c8b6 --- /dev/null +++ b/docs/usermanuals/en/concepts/choosing-trainer.md @@ -0,0 +1,101 @@ +--- +title: Choosing a Trainer +description: A decision tree for picking among SFT, DPO, SimPO, KTO, ORPO, and GRPO. +--- + +# Choosing a Trainer + +The single biggest decision in a fine-tuning project is which trainer to use — and the right answer is almost always determined by your data, not your preferences. + +## Decision tree + +```mermaid +flowchart TD + Start{What kind of
data do you have?} + Q1[Only prompt-completion
pairs] + Q2[Chosen vs rejected
pairs] + Q3[Binary thumbs-up/down
on single responses] + Q4[Both pairs and
preferences] + Q5[Reward function or
verifiable correctness] + + Start --> Q1 + Start --> Q2 + Start --> Q3 + Start --> Q4 + Start --> Q5 + + Q1 --> SFT([SFT]) + Q2 --> Q2a{VRAM tight
or no reference?} + Q2a -->|Yes| SimPO([SimPO]) + Q2a -->|No| DPO([DPO]) + Q3 --> KTO([KTO]) + Q4 --> Q4a{Want one
training stage?} + Q4a -->|Yes| ORPO([ORPO]) + Q4a -->|No| Combo[SFT then DPO] + Q5 --> GRPO([GRPO]) + + classDef start fill:#1c2030,stroke:#f97316,color:#e6e7ec + classDef question fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + classDef result fill:#1c2030,stroke:#22c55e,color:#e6e7ec + class Start,Q2a,Q4a start + class Q1,Q2,Q3,Q4,Q5 question + class SFT,DPO,SimPO,KTO,ORPO,GRPO,Combo result +``` + +## What to look at in your data + +| Data shape | Recommended trainer | +|---|---| +| `{prompt, completion}` rows only | [SFT](#/training/sft) | +| `{prompt, chosen, rejected}` rows | [DPO](#/training/dpo) (or [SimPO](#/training/simpo) if VRAM-tight) | +| `{prompt, response, label: bool}` rows | [KTO](#/training/kto) | +| Mix of SFT and preference rows | [SFT](#/training/sft) → [DPO](#/training/dpo) sequence, or [ORPO](#/training/orpo) for one-stage | +| Programmatic reward (math grader, code tests) | [GRPO](#/training/grpo) | + +## Compute considerations + +If you've decided on a trainer based on data, double-check it fits your VRAM: + +| Trainer | VRAM (relative to SFT same model + max_length) | +|---|---| +| SFT | 1.0× (baseline) | +| ORPO | 1.5× | +| SimPO | 1.2× | +| KTO | 1.5× | +| DPO | 2.0× — keeps reference model in memory | +| GRPO | 2-3× — also keeps reference + reward components | + +:::tip +QLoRA cuts these numbers ~3-4×. A 7B DPO run that needs 22 GB in full precision fits in ~7 GB with QLoRA. See [LoRA, QLoRA, DoRA](#/training/lora). +::: + +## Common starting points + +These templates ship with `forgelm quickstart` and reflect what most teams use as their first run: + +| Goal | Template | Trainer sequence | +|---|---|---| +| Helpful + safe customer-support bot | `customer-support` | SFT → DPO | +| Code-completion model | `code-assistant` | SFT → ORPO | +| Domain expert from your PDFs | `byod-domain-expert` | SFT only | +| Math reasoning | `math-reasoning` | GRPO with format-shaping reward | +| Turkish medical Q&A | `medical-qa-tr` | SFT only | + +## Anti-patterns + +:::warn +**"DPO without SFT first."** A common mistake — going straight to DPO on a base model. Without SFT to teach format and content, DPO becomes brittle and the resulting model often produces malformed outputs. +::: + +:::warn +**"GRPO for everything."** GRPO is powerful for tasks with verifiable correctness (math problems with numerical answers, code with passing tests). For open-ended quality preferences, DPO is more stable and easier to debug. +::: + +:::warn +**"Skipping data audit because the data 'looks fine'."** [Audit your data first](#/data/audit) — a leaky train/test split or PII in your dataset is far more likely to ruin your run than picking the "wrong" trainer. +::: + +## See also + +- [The Alignment Stack](#/concepts/alignment-overview) — broader context of post-training paradigms. +- [Dataset Formats](#/concepts/data-formats) — what JSONL each trainer expects. diff --git a/docs/usermanuals/en/concepts/data-formats.md b/docs/usermanuals/en/concepts/data-formats.md new file mode 100644 index 00000000..d55b2cd9 --- /dev/null +++ b/docs/usermanuals/en/concepts/data-formats.md @@ -0,0 +1,176 @@ +--- +title: Dataset Formats +description: JSONL formats for SFT, DPO, SimPO, KTO, ORPO, and GRPO — what each trainer expects. +--- + +# Dataset Formats + +Every ForgeLM trainer expects a specific JSONL format. ForgeLM auto-detects the format from your file's first row, so you don't have to declare it explicitly — but you do have to produce the right shape. + +## Quick reference + +| Format | Used by | Required fields | +|---|---|---| +| `instructions` | SFT | `prompt`, `completion` | +| `messages` | SFT (multi-turn) | `messages: [{role, content}, …]` | +| `preference` | DPO, SimPO, ORPO | `prompt`, `chosen`, `rejected` | +| `binary` | KTO | `prompt`, `response`, `label` | +| `reward` | GRPO | `prompt` (response generated at training time) | + +## Instructions (single-turn SFT) + +The simplest format — one prompt, one completion per row. + +```json +{"prompt": "What is the capital of France?", "completion": "Paris."} +{"prompt": "Translate 'hello' to Turkish.", "completion": "Merhaba."} +``` + +Optional fields: +- `system` — system prompt prepended to the conversation. +- `metadata` — arbitrary dict; preserved in audit logs but not used at training time. + +## Messages (multi-turn SFT) + +The native HuggingFace chat format. Use this when conversations span multiple turns. + +```json +{"messages": [ + {"role": "system", "content": "You are a polite customer-support agent."}, + {"role": "user", "content": "How do I cancel my subscription?"}, + {"role": "assistant", "content": "From Settings → Billing → Cancel subscription…"}, + {"role": "user", "content": "Will I be charged again?"}, + {"role": "assistant", "content": "No. Your access continues until the end of the billing period."} +]} +``` + +Roles: `system`, `user`, `assistant`. Tool-call roles (`tool`, `function`) are also supported when the chat template defines them. + +:::tip +The chat template applied at training time comes from the model's tokeniser. ForgeLM uses `tokenizer.apply_chat_template()` so a model trained on Llama 3 chat format will be served correctly by Llama 3 chat clients without you doing anything special. +::: + +## Preference (DPO / SimPO / ORPO) + +Each row is a triplet: a prompt, a preferred response, a dispreferred response. + +```json +{ + "prompt": "How do I cancel my subscription?", + "chosen": "From Settings → Billing → Cancel subscription. Your access continues until the end of the billing period.", + "rejected": "Just stop paying lol." +} +``` + +Optional: +- `system` — system prompt for both responses. +- `prompt_messages` — multi-turn prompt as an array (rare; use this when the prompt is itself a conversation). + +The audit (`forgelm audit`) flags rows where `chosen == rejected` — a common bug in preference-collection pipelines. + +## Binary (KTO) + +Single response with a thumbs-up/down label. Simpler to collect than paired preferences when you have user feedback streams. + +```json +{ + "prompt": "How do I cancel my subscription?", + "response": "Just stop paying lol.", + "label": false +} +{ + "prompt": "How do I cancel my subscription?", + "response": "From Settings → Billing → Cancel subscription…", + "label": true +} +``` + +Field meanings: +- `label: true` → desirable response (thumbs-up) +- `label: false` → undesirable response (thumbs-down) + +KTO needs both classes — at minimum 5-10% of your data should be the minority class for stable training. + +## Reward (GRPO) + +GRPO doesn't ship completions — it generates them at training time. You provide prompts, ForgeLM samples responses, scores them with your reward function, and updates the policy. + +```json +{"prompt": "Solve: 17 × 23 = ?", "ground_truth": "391"} +{"prompt": "Solve: 144 ÷ 12 = ?", "ground_truth": "12"} +``` + +The `ground_truth` field is opaque to ForgeLM — it's passed to your reward function: + +```python +# my_reward.py +def reward(prompt: str, response: str, ground_truth: str) -> float: + """Return a scalar in [-1, 1] (or any bounded range).""" + answer = extract_number(response) # your parsing logic + if answer is None: + return -0.5 # malformed + return 1.0 if answer == int(ground_truth) else -1.0 +``` + +In your YAML: + +```yaml +training: + trainer: "grpo" + grpo: + reward_function: "my_reward.reward" +``` + +See [GRPO](#/training/grpo) for the built-in format/length shaping rewards. + +## Multi-dataset mixing + +You can train on a mix of datasets with custom proportions: + +```yaml +datasets: + - path: "data/policies.jsonl" + format: "messages" + weight: 0.7 + - path: "data/general-qa.jsonl" + format: "instructions" + weight: 0.3 +``` + +Weights sum to 1.0; each batch is sampled according to those probabilities. + +## Auto-detection + +If you don't specify `format:`, ForgeLM inspects the first non-empty row: + +| Row contains | Detected as | +|---|---| +| `messages` array | `messages` | +| `chosen` and `rejected` | `preference` | +| `response` and `label` (bool) | `binary` | +| `prompt` and `completion` | `instructions` | +| `prompt` only | `reward` | + +:::warn +Auto-detection happens once per file. If your JSONL mixes formats (some `instructions` rows alongside `preference` rows), the loader will misroute the second-format rows. Use separate files and reference both via `datasets:`. +::: + +## Validating your data + +Always run `forgelm audit` before training: + +```shell +$ forgelm audit data/preferences.jsonl +✓ format: preference (12,400 rows, 3 splits) +✓ no PII detected (5 medium severity, see report) +⚠ 12 chosen-rejected identical rows — likely collection bug +✓ no cross-split leakage +``` + +See [Dataset Audit](#/data/audit) for full audit semantics. + +## See also + +- [Document Ingestion](#/data/ingestion) — convert PDF/DOCX/EPUB/Markdown into these JSONL formats. +- [Dataset Audit](#/data/audit) — run before training. +- [Choosing a Trainer](#/concepts/choosing-trainer) — match your data to the right trainer. diff --git a/docs/usermanuals/en/data/audit.md b/docs/usermanuals/en/data/audit.md new file mode 100644 index 00000000..026a89c1 --- /dev/null +++ b/docs/usermanuals/en/data/audit.md @@ -0,0 +1,161 @@ +--- +title: Dataset Audit +description: Catch PII, secrets, leakage, near-duplicates, and quality issues before they ruin your training run. +--- + +# Dataset Audit + +`forgelm audit` is a CPU-only, streaming pre-flight check for your training data. It catches the bugs that make models fail safety review, leak secrets in production, or memorise the test set. Run it before every training job. + +```mermaid +flowchart LR + A[JSONL data] --> B[forgelm audit] + B --> C[PII scan] + B --> D[Secrets scan] + B --> E[Near-dup scan] + B --> F[Quality filter] + B --> G[Language detect] + B --> H[Cross-split leak check] + C & D & E & F & G & H --> I[data_audit_report.json] + classDef io fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef check fill:#161a24,stroke:#f97316,color:#e6e7ec + class A,B,I io + class C,D,E,F,G,H check +``` + +## Quick example + +```shell +$ forgelm audit data/preferences.jsonl --output ./audit/ +✓ format: preference (12,400 rows, 3 splits) +⚠ PII: 12 emails, 3 phone, 1 IBAN (medium severity, see report) +✓ secrets: 0 detected +⚠ near-duplicate pairs: 47 (LSH-banded simhash, threshold 3) +✗ chosen-rejected identical: 12 rows (likely collection bug) +✓ language: 99.2% Turkish, 0.8% English +✓ no cross-split leakage + +audit complete — see ./audit/data_audit_report.json +``` + +The exit code reflects severity: + +| Exit | Meaning | +|---|---| +| `0` | Clean. Safe to train. | +| `2` | Warnings. Review the report; training will work but quality may suffer. | +| `3` | Errors. Cross-split leakage or other show-stoppers detected. Fix before training. | + +## What audit checks + +### PII (personally identifiable information) + +Detects emails, phone numbers, credit card numbers (Luhn-validated), IBAN, and national IDs (TR, DE, FR, US-SSN). Tags rows by severity. See [PII Masking](#/data/pii-masking). + +### Secrets + +Detects AWS keys, GitHub Personal Access Tokens, Slack tokens, OpenAI keys, Google API keys, JWTs, full PEM private-key blocks, Azure storage strings. See [Secrets Scrubbing](#/data/secrets). + +### Near-duplicate detection + +Two algorithms: +- **LSH-banded simhash** (default) — exact recall, fast, good for <50K rows. +- **MinHash LSH** — approximate, scales to millions of rows. + +See [Deduplication](#/data/deduplication) for the trade-offs. + +### Quality filter + +Heuristics borrowed from Gopher, C4, RefinedWeb research. Flags rows with low alpha ratio, abnormal word lengths, repeated lines, or short paragraphs. Conservative — never silently drops rows. See [Quality Filter](#/data/quality-filter). + +### Language detection + +Uses `langdetect` to identify the dominant language per row. Reports top-3 across the dataset. Catches the "supposed to be Turkish but 12% slipped in as English" class of bugs. See [Language Detection](#/data/language-detection). + +### Cross-split leakage + +Compares train vs validation vs test rows for exact and near-duplicate matches. The single most expensive evaluation bug — leakage means your reported metrics are inflated. Audit refuses to certify a leaky split. See [Cross-Split Leakage](#/data/leakage). + +### Format-specific checks + +For **preference** datasets, audit also flags: +- Rows where `chosen == rejected` (collection bug) +- Rows where `chosen` is shorter than `rejected` by more than 10× (likely accidental swap) +- Empty `chosen` or `rejected` + +For **binary** (KTO) datasets: +- Severe class imbalance (>99/1) +- Empty responses +- Non-boolean labels + +## CLI flags + +| Flag | Description | +|---|---| +| `--output PATH` | Output directory for the audit report (default `./audit/`). | +| `--strict` | Treat warnings as errors. Exit 2 instead of 0 on any flag. | +| `--dedup-algo {simhash,minhash}` | Override default near-dup algorithm. | +| `--dedup-threshold N` | Hamming distance threshold for simhash (default 3). | +| `--skip-pii / --skip-secrets / ...` | Selectively disable individual checks. | +| `--sample-rate FLOAT` | Audit a random subsample (e.g. `0.1` for 10%). For very large datasets. | + +## What's in the report + +`data_audit_report.json` is structured for both human reading and CI integration: + +```json +{ + "format": "preference", + "row_count": 12400, + "splits": {"train": 10000, "val": 1200, "test": 1200}, + "pii_summary": { + "email": 12, + "phone": 3, + "iban": 1, + "severity": "medium" + }, + "secrets_summary": {"total": 0}, + "near_duplicate_pairs": 47, + "cross_split_overlap": 0, + "quality_flags": { + "short_response": 24, + "repeated_lines": 0, + "abnormal_word_length": 12 + }, + "language_distribution": {"tr": 0.992, "en": 0.008}, + "preference_specific": { + "identical_chosen_rejected": 12, + "empty_chosen": 0, + "swapped_likely": 0 + }, + "verdict": "warnings" +} +``` + +CI integrations parse `verdict` and individual counts to gate merges: + +```yaml +# .github/workflows/data.yml +- name: Audit data + run: forgelm audit data/train.jsonl --strict +``` + +## Common pitfalls + +:::warn +**Skipping audit on "trusted" data.** Even data from your own production logs can have surprises — a recent rotation of API keys leaks into telemetry, a GDPR-deletion request creates dangling IDs. Audit defends against your own future mistakes. +::: + +:::warn +**Using `--sample-rate` on a small dataset.** Sampling makes sense for million-row corpora; for <10K rows, audit the whole thing — it takes seconds anyway. +::: + +:::tip +**Save audit reports per-version.** Commit `data_audit_report.json` to git alongside your dataset version. Future audits can diff against the historical report and tell you "we had 12 PII flags last time, now we have 47 — what changed in the data pipeline?" +::: + +## See also + +- [PII Masking](#/data/pii-masking), [Secrets Scrubbing](#/data/secrets), [Deduplication](#/data/deduplication) — individual checks in detail. +- [Annex IV](#/compliance/annex-iv) — how audit reports flow into compliance artifacts. +- [Configuration Reference](#/reference/configuration) — `compliance.data_audit_artifact` field. diff --git a/docs/usermanuals/en/data/deduplication.md b/docs/usermanuals/en/data/deduplication.md new file mode 100644 index 00000000..5ac95e40 --- /dev/null +++ b/docs/usermanuals/en/data/deduplication.md @@ -0,0 +1,115 @@ +--- +title: Near-Duplicate Detection +description: LSH-banded simhash and MinHash LSH for catching near-duplicates in training data. +--- + +# Near-Duplicate Detection + +Duplicates and near-duplicates inflate your training distribution towards whatever's repeated, and — when they straddle train/eval splits — make your evaluation metrics meaningless. ForgeLM ships two algorithms: simhash for accuracy and small-to-medium corpora, MinHash LSH for scale. + +## Algorithm choice + +| Algorithm | Recall | Speed | Best for | +|---|---|---|---| +| **LSH-banded simhash** (default) | Exact within Hamming threshold | ~50K rows/sec | Corpora < 50K rows | +| **MinHash LSH** | Approximate (>95% of true duplicates) | ~500K rows/sec | Corpora > 50K rows | + +ForgeLM auto-selects based on row count — simhash for small, MinHash for large — but you can override via `--dedup-algo`. + +## Quick example + +```shell +$ forgelm audit data/train.jsonl --dedup-threshold 3 +⚠ near-duplicate pairs: 47 (LSH-banded simhash, threshold 3) + +$ jq '.near_duplicates[]' audit/data_audit_report.json | head +{"row_a": 1240, "row_b": 4521, "hamming": 1, "similarity": 0.984} +{"row_a": 9012, "row_b": 9013, "hamming": 0, "similarity": 1.0} +``` + +A `hamming: 0` means *exact* duplicates (same simhash); higher values are progressively less similar. + +## Threshold tuning + +The `--dedup-threshold` is a Hamming distance on the 64-bit simhash. Defaults are: + +| Threshold | Captures | False-positive rate | +|---|---|---| +| 0 | Exact duplicates only | ~0% | +| 1-2 | Trivial-edit duplicates ("Hello!" vs "Hello.") | <1% | +| **3** (default) | Paraphrases with shared structure | 1-2% | +| 5+ | Loose paraphrases; high false-positive rate | 5-15% | + +Most teams stick with 3. + +## What near-dup catches that exact-match doesn't + +```text +Row A: "Welcome to our customer support. How can I help you today?" +Row B: "Welcome to our customer support — how can I help you today?" +``` + +Exact-match misses these (different punctuation). Simhash with threshold 3 catches them. + +```text +Row A: "Send your CV to ali@example.com" +Row B: "Send your CV to ali@example.com or call us" +``` + +Threshold 3 also catches these (same first half, slight extension). + +## Cross-split awareness + +Audit runs near-dup detection both *within* and *across* splits. Cross-split duplicates are the high-priority bug — they make your benchmark scores unreliable. Audit's `cross_split_overlap` field reports how many train rows have a near-duplicate in validation or test. See [Cross-Split Leakage](#/data/leakage). + +## MinHash LSH for scale + +For corpora over 50K rows, switch to MinHash: + +```shell +$ forgelm audit data/large.jsonl --dedup-algo minhash --num-perm 256 +✓ near-duplicate pairs: 1,247 (MinHash LSH, 256 permutations, threshold 0.85) +``` + +MinHash trades small accuracy for big speed — typical recall is >95% of true duplicates while running 10× faster than simhash on million-row datasets. + +| MinHash flag | Description | +|---|---| +| `--num-perm` | Number of hash permutations (default 128). More = higher accuracy, more memory. | +| `--minhash-threshold` | Jaccard similarity threshold (default 0.85). | +| `--minhash-bands` | LSH banding parameter (default auto-derived from threshold). | + +## Streaming behaviour + +Both algorithms are streaming — they don't load the whole dataset into memory. A 10M-row corpus dedupes in a few minutes on a laptop CPU. + +## Removing duplicates + +`forgelm audit` *detects* duplicates; it doesn't remove them by default (data modification is intentional). To deduplicate: + +```shell +$ forgelm audit data/train.jsonl --remove-duplicates --output-clean data/train.dedup.jsonl +✓ removed 47 near-duplicate rows; wrote data/train.dedup.jsonl (12,353 rows) +``` + +When duplicates are within a single split, ForgeLM keeps the first occurrence. Across splits, it keeps the train-side row by default and removes from validation/test (configurable). + +## Common pitfalls + +:::warn +**Threshold too aggressive.** Hamming threshold 5+ on simhash will flag legitimately different examples as duplicates. Stick with 3 unless you've measured false-positive rate on your specific data. +::: + +:::warn +**MinHash permutations too low.** `--num-perm 64` saves memory but recall drops to ~85%. Stay above 128 for production use. +::: + +:::tip +**Run dedup BEFORE manually splitting train/val/test.** If your splits are produced upstream and have leakage, you can't fix that with deduplication; you have to re-split. Audit on the combined dataset before splitting catches this. +::: + +## See also + +- [Dataset Audit](#/data/audit) — runs dedup as part of the standard audit. +- [Cross-Split Leakage](#/data/leakage) — the highest-priority deduplication concern. +- [Quality Filter](#/data/quality-filter) — sister feature for catching low-quality rows. diff --git a/docs/usermanuals/en/data/ingestion.md b/docs/usermanuals/en/data/ingestion.md new file mode 100644 index 00000000..50b6ca57 --- /dev/null +++ b/docs/usermanuals/en/data/ingestion.md @@ -0,0 +1,122 @@ +--- +title: Document Ingestion +description: Convert PDF, DOCX, EPUB, TXT, and Markdown into SFT-ready JSONL with one command. +--- + +# Document Ingestion + +Most fine-tuning datasets don't start as JSONL — they start as PDFs, contracts, EPUBs, or messy Markdown notes. `forgelm ingest` walks your input directory, extracts text in a format-aware way, and emits SFT-ready JSONL. + +```mermaid +flowchart LR + A[Input dir
PDF/DOCX/EPUB/MD] --> B[Format detect] + B --> C[Extract text
preserve structure] + C --> D[Chunk by tokens
or by Markdown] + D --> E[Apply masking
PII + secrets] + E --> F[Output JSONL] + classDef io fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef step fill:#161a24,stroke:#f97316,color:#e6e7ec + class A,F io + class B,C,D,E step +``` + +## Quick example + +```shell +$ forgelm ingest ./policies/ \ + --recursive \ + --strategy markdown \ + --max-tokens 1024 \ + --pii-mask --secrets-mask \ + --output data/policies.jsonl +✓ scanned 47 files (12 PDF, 8 DOCX, 27 MD) +✓ extracted 12,240 chunks (avg 743 tokens) +✓ masked 18 PII matches, 0 secret matches +✓ wrote data/policies.jsonl (8.2 MB) +``` + +## Supported formats + +| Format | Extractor | Notes | +|---|---|---| +| **PDF** | `pypdf` | Header/footer dedup, table extraction (best-effort). | +| **DOCX** | `python-docx` | Tables emit as Markdown tables; preserves headings. | +| **EPUB** | `ebooklib` | Strips navigation/index; preserves chapter structure. | +| **TXT** | built-in | Treated as one document; chunked by `--max-tokens`. | +| **Markdown** | built-in | Markdown-aware splitter respects heading hierarchy. | + +Install the ingestion extras: `pip install 'forgelm[ingestion]'`. See [Installation](#/getting-started/installation). + +## Chunking strategies + +| Strategy | Behaviour | Best for | +|---|---|---| +| `tokens` | Hard cap at `--max-tokens` per chunk; tries to split on sentence boundaries. | Plain text, mixed content. | +| `markdown` | Splits on Markdown headings (h1/h2/h3), respects hierarchy. | Documentation, structured corpora. | +| `paragraph` | One chunk per paragraph (or merged paragraphs to fit). | Books, prose. | +| `sentence` | One chunk per sentence (rare; for very fine-grained data). | NLI tasks, short Q&A. | + +Most teams pick `markdown` for documentation and `tokens` for everything else. + +## Output formats + +By default, `forgelm ingest` emits the `instructions` format with synthetic prompts: + +```json +{"prompt": "Summarise the following passage.", "completion": "Section 4.2 of the policy specifies…", "metadata": {"source": "policy.pdf", "chunk": 17}} +``` + +For domain-expert SFT, you typically want `--format raw` which emits the chunk as-is and lets you generate prompts later (or use it for continued pre-training): + +```json +{"text": "Section 4.2: All payment processing must comply with PCI-DSS standards…", "metadata": {"source": "policy.pdf", "chunk": 17}} +``` + +For Q&A datasets, use `--format qa` with a prompt-generation LLM: + +```yaml +ingestion: + format: "qa" + qa_generator: + model: "openai:gpt-4o-mini" # or local model + prompts_per_chunk: 3 +``` + +## CLI flags + +| Flag | Description | +|---|---| +| `--recursive` | Walk subdirectories. | +| `--strategy {tokens,markdown,paragraph,sentence}` | Chunking strategy. | +| `--max-tokens N` | Token cap per chunk (default 1024). | +| `--overlap N` | Sliding-window overlap between chunks (default 0). | +| `--pii-mask` | Mask emails, phone, IDs, IBAN before writing. See [PII Masking](#/data/pii-masking). | +| `--secrets-mask` | Redact AWS keys, GitHub PATs, JWTs, etc. See [Secrets Scrubbing](#/data/secrets). | +| `--language LANG` | Force a language (default: auto-detect per chunk). | +| `--include "*.pdf,*.md"` | Glob patterns to include. | +| `--exclude "drafts/*"` | Glob patterns to exclude. | +| `--output PATH` | Output file (`.jsonl`). | + +## Common pitfalls + +:::warn +**Forgetting `--pii-mask`.** The default is *no* masking, on the principle of "don't silently modify your data". For real corpora, enable it explicitly. The audit step ([Dataset Audit](#/data/audit)) will flag PII regardless, but better to mask at ingest. +::: + +:::warn +**Pure-image PDFs.** ForgeLM doesn't ship OCR. If your PDFs are scanned images, run them through Tesseract or a commercial OCR first. +::: + +:::warn +**`--max-tokens` larger than the model's context.** Chunks longer than `model.max_length` will be truncated at training time, losing the tail. Match `--max-tokens` to the training context. +::: + +:::tip +**Always audit after ingest.** A clean ingest doesn't mean a clean dataset. Run `forgelm audit data/output.jsonl` to check for cross-split leakage, near-duplicates, and PII the masking missed. +::: + +## See also + +- [Dataset Audit](#/data/audit) — the next step after ingest. +- [PII Masking](#/data/pii-masking) — how the masking works. +- [Dataset Formats](#/concepts/data-formats) — what each output format looks like. diff --git a/docs/usermanuals/en/data/language-detection.md b/docs/usermanuals/en/data/language-detection.md new file mode 100644 index 00000000..08007d2a --- /dev/null +++ b/docs/usermanuals/en/data/language-detection.md @@ -0,0 +1,81 @@ +--- +title: Language Detection +description: Per-row language identification — catch the "supposed to be Turkish but 12% slipped in as English" bug. +--- + +# Language Detection + +Real-world datasets are often nominally one language but accidentally contain others — copy-pasted English documentation in a Turkish corpus, French legal boilerplate in a Spanish dataset. ForgeLM detects per-row language and reports the distribution at audit time. + +## Quick example + +```shell +$ forgelm audit data/medical-tr.jsonl +✓ language: 99.2% tr, 0.5% en, 0.3% other + 12 rows in 'en' (likely accidental) + 5 rows in 'mixed' (containing both languages) +``` + +The audit report breaks down per-row language and lists indices of outliers, so you can inspect: + +```shell +$ jq '.language_outliers[:3]' audit/data_audit_report.json +[ + {"row": 1240, "detected": "en", "expected": "tr", "snippet": "Lorem ipsum dolor..."}, + {"row": 4521, "detected": "en", "expected": "tr", "snippet": "Patient should call..."}, + {"row": 9012, "detected": "mixed", "expected": "tr", "snippet": "Hasta günde 3 kez two..."} +] +``` + +## Detector + +Uses `langdetect` (a pure-Python port of Google's CLD2). Supports 55+ languages out of the box. Performance: ~1ms per row, no GPU. + +For very short rows (<50 characters), language detection becomes unreliable — ForgeLM marks those as `unknown` rather than guessing. + +## Configuration + +```yaml +audit: + language_detection: + enabled: true + expected: "tr" # explicit expected language + min_chars: 50 # rows shorter than this are 'unknown' + mixed_threshold: 0.3 # if second-language confidence > 30%, mark 'mixed' +``` + +If you don't set `expected`, audit reports the distribution without flagging outliers — useful for genuinely multilingual datasets. + +## Per-language Distribution Report + +```json +{ + "language_distribution": { + "tr": 0.992, + "en": 0.005, + "ar": 0.001, + "unknown": 0.002 + }, + "language_outliers": 17, + "expected": "tr" +} +``` + +## Common pitfalls + +:::warn +**Detecting language on extracted PDF text.** PDF extraction sometimes preserves runs of English boilerplate ("Confidential", "Page 1 of N", "© 2026 Company") that throw off detection on otherwise-Turkish content. Pre-filter these in ingest. +::: + +:::warn +**Setting `min_chars` too low.** Short rows produce noisy detection. Stay above 50; 100 is even safer for quality reports. +::: + +:::tip +**Multi-language datasets.** If your dataset is intentionally multilingual (translation pairs, multilingual chat), don't set `expected` — let audit just report the distribution and flag rows that are mixed within a single document. +::: + +## See also + +- [Dataset Audit](#/data/audit) — runs language detection as part of standard audit. +- [Document Ingestion](#/data/ingestion) — `--language` flag for forced language at ingest time. diff --git a/docs/usermanuals/en/data/leakage.md b/docs/usermanuals/en/data/leakage.md new file mode 100644 index 00000000..6cc00d5a --- /dev/null +++ b/docs/usermanuals/en/data/leakage.md @@ -0,0 +1,121 @@ +--- +title: Cross-Split Leakage +description: Detect when train rows also appear in validation or test — the most expensive evaluation bug. +--- + +# Cross-Split Leakage + +Train rows that also appear in validation or test inflate your evaluation metrics in misleading ways. The model "knows" the test answer because it saw it during training. Reported scores look good; production performance disappoints. + +ForgeLM's cross-split leakage check is the single most important audit step. It runs every time you call `forgelm audit` and refuses to certify a leaky split. + +## How leakage happens + +The usual culprits: + +1. **Random shuffling without grouping.** Splitting by row randomly puts duplicate rows on both sides. +2. **Augmentation before splitting.** Generating paraphrases of existing rows, then splitting — the original and paraphrase end up on different sides. +3. **Multiple sources of the same content.** A FAQ in your training corpus and the same FAQ in your eval set, ingested separately. +4. **Web crawls overlapping with benchmarks.** Training data crawled the web; the benchmark publisher also published their test set on the web. + +## What the check does + +```mermaid +flowchart LR + Train[train.jsonl] --> H[Hash all rows] + Val[val.jsonl] --> H + Test[test.jsonl] --> H + H --> E[Exact-match index] + H --> N[Near-dup simhash] + E --> R[Cross-split overlap report] + N --> R + classDef io fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef step fill:#161a24,stroke:#f97316,color:#e6e7ec + classDef out fill:#1c2030,stroke:#22c55e,color:#e6e7ec + class Train,Val,Test io + class H,E,N step + class R out +``` + +For every train row, ForgeLM checks: +- **Exact match** in val/test (any field that matters: `prompt`, `chosen`, `response`, etc.). +- **Near-duplicate** (Hamming threshold 3 simhash) in val/test. + +Any match is reported. If the leakage rate is over the configured threshold, audit exits non-zero. + +## Quick example + +```shell +$ forgelm audit data/ # audits train.jsonl + val.jsonl + test.jsonl +✗ cross-split overlap detected: + train ↔ val: 47 exact, 12 near-dup + train ↔ test: 23 exact, 5 near-dup + val ↔ test: 0 + +Audit refuses to certify these splits. Run `--show-leakage` for indices. + +exit code: 3 +``` + +```shell +$ forgelm audit data/ --show-leakage +{train: 1240, val: 312, type: "exact", text: "How do I cancel..."} +{train: 4521, val: 890, type: "near-dup", hamming: 2, ...} +``` + +## How to fix it + +1. **Re-split the data**, this time grouping at the source level (don't split paraphrases, group documents). Use the `--group-by` flag in your splitter. +2. **Re-extract** if leakage came from duplicate ingestion (the same FAQ ingested twice). +3. **Remove** the leaked rows from the smaller split (audit's `--remove-cross-split-overlap` does this — but think before relying on it). + +```shell +$ forgelm audit data/ --remove-cross-split-overlap=val \ + --output-clean data/clean/ +✓ removed 47 cross-split rows from val (kept train side) +``` + +## Configuration + +```yaml +audit: + leakage_check: + enabled: true + threshold: 0 # zero tolerance — fail audit at any leakage + near_dup_hamming: 3 # match threshold + fields_to_check: ["prompt", "chosen", "response"] + fail_severity: "error" # `error` blocks training, `warn` just logs +``` + +Most teams use the default — zero tolerance. If you have a very large dataset where some leakage is unavoidable, raise `threshold` to a small fraction (e.g. 0.001) but document why. + +## Why "near-dup" matters here + +Exact-match leakage is rare in modern pipelines because everyone deduplicates. But near-dup leakage is the silent killer: + +```text +Train: "How do I cancel my subscription?" +Test: "How do I cancel my subscription" +``` + +Different by one character — exact-match misses it; the model treats them as identical at training time anyway. Near-dup catches this. + +## Common pitfalls + +:::warn +**Splitting after augmentation.** If you generate paraphrases of training data, then random-split, the paraphrase ends up on the other side. Always split *before* augmenting. +::: + +:::warn +**Trusting upstream splits.** If your dataset was published with predefined train/val/test splits, audit them. Public datasets sometimes have known leakage that has propagated for years. +::: + +:::danger +**Bypassing the leakage check to "ship something today".** The price of a leaky run is reporting good benchmark numbers, deploying, and discovering production performance is much worse. The loss of trust costs more than the delay would have. +::: + +## See also + +- [Dataset Audit](#/data/audit) — runs leakage check by default. +- [Deduplication](#/data/deduplication) — same simhash backend. +- [Annex IV](#/compliance/annex-iv) — leakage report is part of the compliance bundle. diff --git a/docs/usermanuals/en/data/pii-masking.md b/docs/usermanuals/en/data/pii-masking.md new file mode 100644 index 00000000..a9c81e1d --- /dev/null +++ b/docs/usermanuals/en/data/pii-masking.md @@ -0,0 +1,139 @@ +--- +title: PII Masking +description: Detect and redact emails, phones, credit cards, IBAN, and national IDs at ingest time. +--- + +# PII Masking + +Personal data in your training set is a regulatory hazard (GDPR Article 5(1)(c) — data minimisation) and an operational hazard (the model memorises and emits it). ForgeLM's PII masker detects nine categories of PII and redacts them at ingest time, before chunks land in JSONL. + +## What gets detected + +| Category | Examples | How | +|---|---|---| +| **Email** | `alice@example.com` | RFC 5321-compatible regex | +| **Phone** | `+90 532 123 45 67`, `(555) 123-4567` | E.164-compatible patterns + locale variants | +| **Credit card** | `4111-1111-1111-1111` | Visa/MC/Amex/Discover patterns + Luhn check (no false-positives on lookalikes) | +| **IBAN** | `TR12 0006 4000 0011 2345 6789 01` | Country-aware checksum | +| **National ID — Turkey** | 11-digit TC kimlik | Modulo-10 + modulo-11 checksums | +| **National ID — Germany** | Steuer-ID | Format + checksum | +| **National ID — France** | NIR (social security) | Format + key validation | +| **US SSN** | `123-45-6789` | Format + reserved-block exclusions | +| **IPv4 / IPv6** | `192.168.1.1`, `2001:db8::1` | Standard regex (off by default; opt in) | + +## Quick example + +At ingest time: + +```shell +$ forgelm ingest ./policies/ \ + --recursive --strategy markdown \ + --pii-mask \ + --output data/policies.jsonl +✓ masked 18 PII matches across 12,240 chunks +``` + +After ingest, every match is replaced with a tagged placeholder: + +```text +Before: "Send your CV to ali@example.com or call +90 532 555 7890." +After: "Send your CV to [EMAIL_REDACTED] or call [PHONE_REDACTED]." +``` + +The placeholder is consistent across the dataset, so a model can still learn that *some* email goes in that slot — just not the specific one. + +## Tags emitted + +| Tag | Replaces | +|---|---| +| `[EMAIL_REDACTED]` | Email addresses | +| `[PHONE_REDACTED]` | Phone numbers | +| `[CREDITCARD_REDACTED]` | Credit card numbers (Luhn-validated) | +| `[IBAN_REDACTED]` | IBANs | +| `[ID_TR_REDACTED]` | TC kimlik numbers | +| `[ID_DE_REDACTED]` | Steuer-IDs | +| `[ID_FR_REDACTED]` | NIR numbers | +| `[SSN_REDACTED]` | US SSNs | +| `[IP_REDACTED]` | IP addresses | + +## Conservative-by-design + +The PII regexes are deliberately tuned for **low false-positive rate**. They prefer to miss a borderline match (false negative) than to redact a non-PII string in your prose (false positive). Reasons: + +1. False positives silently corrupt your data — replacing legitimate words with `[EMAIL_REDACTED]` ruins examples. +2. The audit step catches what masking missed; you can decide per-row whether to fix or drop. +3. Aggressive regexes have caused real-world ML pipeline outages (the Phase 11.5 incident is documented in `docs/standards/regex.md`). + +If you need stricter detection — for instance, a high-stakes legal corpus — pair the masker with a manual review step. Don't push the regexes harder. + +## Audit-only mode + +To detect without modifying: + +```shell +$ forgelm audit data/policies.jsonl +⚠ PII: 18 emails, 4 phone, 2 IBAN (medium severity) +``` + +The audit report lists row indices and offsets, so you can inspect specific cases. + +## Locales + +| Locale | Phone | National ID | Notes | +|---|---|---|---| +| TR (default) | E.164 + Turkish formats | TC kimlik | Most heavily tuned. | +| DE | E.164 + German formats | Steuer-ID | | +| FR | E.164 + French formats | NIR | | +| US | E.164 + (xxx) xxx-xxxx | SSN with reserved-block exclusion | | +| Global | E.164 only | none | Fallback for unknown locales. | + +Set the locale at ingest: + +```shell +$ forgelm ingest ./docs/ --pii-mask --pii-locale de +``` + +Or in YAML: + +```yaml +ingestion: + pii_mask: + enabled: true + locale: "de" + categories: ["email", "phone", "iban", "id_de"] + skip: ["ip"] # don't redact IPs +``` + +## Programmatic API + +For pipelines that need PII detection outside ingest: + +```python +from forgelm.data_audit import detect_pii, mask_pii + +text = "Email: ali@example.com, Phone: +90 532 555 7890" +hits = detect_pii(text, locale="tr") +print(hits) +# [{'category': 'email', 'span': (7, 22), 'value': 'ali@example.com'}, +# {'category': 'phone', 'span': (31, 47), 'value': '+90 532 555 7890'}] + +masked = mask_pii(text, locale="tr") +print(masked) +# Email: [EMAIL_REDACTED], Phone: [PHONE_REDACTED] +``` + +## Common pitfalls + +:::warn +**Relying on PII masking for compliance certification.** PII masking is a defence-in-depth measure, not a certification. For a high-stakes corpus (legal, medical), pair masking with a manual review step. ForgeLM ships an `audit` mode that flags PII without modifying so you can review. +::: + +:::warn +**Custom PII categories without testing.** The repo's `regex.md` standard documents 8 hard rules for adding new patterns. Skipping the testing checklist is how false-positive bugs ship. +::: + +## See also + +- [Dataset Audit](#/data/audit) — runs PII detection without modifying data. +- [Secrets Scrubbing](#/data/secrets) — sister feature for credentials. +- [GDPR / KVKK](#/compliance/gdpr) — regulatory context. diff --git a/docs/usermanuals/en/data/quality-filter.md b/docs/usermanuals/en/data/quality-filter.md new file mode 100644 index 00000000..92930db1 --- /dev/null +++ b/docs/usermanuals/en/data/quality-filter.md @@ -0,0 +1,98 @@ +--- +title: Quality Filter +description: Heuristic filters from Gopher, C4, and RefinedWeb for catching low-quality training rows. +--- + +# Quality Filter + +Not all rows in your training data are equally useful. Boilerplate, OCR errors, repeated lines, and pure-symbol noise dilute the signal. ForgeLM's quality filter applies heuristics drawn from the Gopher, C4, and RefinedWeb research lineages — conservatively, so it never silently drops rows. + +## What gets flagged + +| Heuristic | What it catches | +|---|---| +| **Low alpha ratio** | `<55%` alphabetic characters — usually code dumps, log spam, or pure symbols. | +| **Abnormal mean word length** | Words averaging `<3` or `>10` characters — often OCR garbage or URL-only rows. | +| **Repeated line ratio** | Rows where `>30%` of lines are duplicated — boilerplate or extraction artifacts. | +| **Short content** | Total length below a configurable minimum — often empty after extraction. | +| **Bullet-only rows** | Rows where `>90%` of lines start with bullet markers — usually extracted nav menus. | +| **Symbol density** | Excessive `_-=#*` density — usually rendered tables or pre-formatted text. | + +Each row gets a `quality_flags` list in the audit report. The filter never automatically drops; it's your call. + +## Quick example + +```shell +$ forgelm audit data/ingested.jsonl +⚠ quality flags: + short_response: 24 + repeated_lines: 12 + abnormal_word_length: 6 + bullet_only: 3 +``` + +To drop flagged rows: + +```shell +$ forgelm audit data/ingested.jsonl --drop-quality-flags --output-clean data/clean.jsonl +✓ dropped 45 rows; wrote data/clean.jsonl (12,355 rows) +``` + +## Tuning thresholds + +```yaml +audit: + quality_filter: + enabled: true + min_alpha_ratio: 0.55 # default 0.55 + min_mean_word_length: 3 # default 3 + max_mean_word_length: 10 # default 10 + max_repeated_line_ratio: 0.30 # default 0.30 + min_content_length: 50 # default 50 characters + max_bullet_ratio: 0.90 # default 0.90 +``` + +For corpora that legitimately violate one of these (e.g. code-heavy datasets violate alpha ratio), turn off the specific check rather than the whole filter: + +```yaml +audit: + quality_filter: + enabled: true + skip: ["min_alpha_ratio"] # code, math, log datasets +``` + +## Conservative-by-default + +The thresholds are tuned to *flag, not drop*. The reasons: + +1. Domain mismatch — a quality filter tuned on web crawls misjudges medical or legal text. +2. Silent dropping is invisible to the user. Better to surface flags and let the human decide. +3. Audit reports are compared across dataset versions; a sudden change in flag counts is informative. + +If you want stricter filtering — for instance, on a public web crawl going into pre-training — pair the filter with a manual review of edge cases. + +## Programmatic API + +```python +from forgelm.data_audit import score_quality + +text = "= = = = = = = =\n* * *\n[no content]" +flags = score_quality(text) +print(flags) +# {'low_alpha_ratio': True, 'symbol_density': True, 'short_content': True} +``` + +## Common pitfalls + +:::warn +**Auto-dropping without review.** Set `--drop-quality-flags` carefully — it removes rows without showing you what got removed. Run `forgelm audit` first to inspect what's flagged. +::: + +:::warn +**Filtering code datasets with default thresholds.** Code has more symbols and shorter mean word length than prose. Either disable the affected checks or use code-specific thresholds. +::: + +## See also + +- [Dataset Audit](#/data/audit) — runs the quality filter as part of standard audit. +- [Document Ingestion](#/data/ingestion) — most quality issues originate at extraction time. diff --git a/docs/usermanuals/en/data/secrets.md b/docs/usermanuals/en/data/secrets.md new file mode 100644 index 00000000..5f9b4315 --- /dev/null +++ b/docs/usermanuals/en/data/secrets.md @@ -0,0 +1,131 @@ +--- +title: Secrets Scrubbing +description: Detect and redact AWS keys, GitHub PATs, JWTs, PEM blocks, and other credentials from training data. +--- + +# Secrets Scrubbing + +Code repositories, support tickets, and operational logs leak credentials. Once those credentials end up in a training set and the model is deployed, anyone who chats with the model can extract them. Secrets scrubbing prevents this at ingest. + +## What gets detected + +| Category | Pattern detected | +|---|---| +| **AWS access keys** | `AKIA[0-9A-Z]{16}` + secret-key heuristics | +| **GitHub PATs** | `ghp_*`, `gho_*`, `ghu_*`, `ghs_*`, `ghr_*` | +| **GitHub fine-grained tokens** | `github_pat_*` | +| **Slack tokens** | `xox[bpars]-*` | +| **OpenAI API keys** | `sk-*` (with length and entropy checks) | +| **Anthropic API keys** | `sk-ant-*` | +| **Google API keys** | `AIza*` | +| **JWTs** | Three-segment base64url (header.payload.signature) | +| **PEM private-key blocks** | `BEGIN ... PRIVATE KEY...END` (RSA, EC, OpenSSH, PGP) | +| **Azure storage strings** | `DefaultEndpointsProtocol=...` | +| **Stripe / SendGrid / Twilio** | Service-specific patterns | + +All matches are replaced with `[REDACTED-SECRET]` (or per-category tags via `--secrets-tag-by-category`). + +## Quick example + +```shell +$ forgelm ingest ./support-tickets/ \ + --recursive \ + --secrets-mask \ + --output data/tickets.jsonl +✓ masked 47 secrets: + aws_access_key: 12 + github_pat: 8 + jwt: 18 + pem_block: 2 + openai_key: 7 +``` + +## What "PEM block" means + +PEM private keys span multiple lines: + +```text +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEA1+... +... +-----END RSA PRIVATE KEY----- +``` + +ForgeLM's PEM detector matches the entire block (BEGIN to END), not just the marker line. The whole block is replaced with `[REDACTED-PEM-BLOCK]`. This avoids the common bug of detecting the BEGIN line but leaving the key body in the JSONL. + +## Audit-only mode + +```shell +$ forgelm audit data/tickets.jsonl --skip-pii +✓ format: instructions (8,400 rows) +⚠ secrets: 47 detected (severity: critical) + 12 AWS access keys + 18 JWTs + ... +``` + +A `critical` severity flags the run for failure if you also pass `--strict`. + +## Programmatic API + +```python +from forgelm.data_audit import detect_secrets, mask_secrets + +text = "Use this key: AKIAIOSFODNN7EXAMPLE and JWT eyJhbGc..." +hits = detect_secrets(text) +print(hits) +# [{'category': 'aws_access_key', 'span': (14, 34), 'value': 'AKIAIOSFODNN7EXAMPLE'}] + +cleaned = mask_secrets(text) +# "Use this key: [REDACTED-SECRET] and JWT [REDACTED-SECRET]..." +``` + +## False-positive guards + +ForgeLM ships secrets detection with stricter false-positive guards than typical "git-secrets"-style tools, because: + +1. False positives in training data corrupt examples (replacing legitimate strings). +2. Many regex-only patterns flag `EXAMPLEKEY` or test fixtures, which makes audit reports useless. + +Specific guards: +- **Entropy threshold** for OpenAI / Anthropic keys (random-looking, not human-readable). +- **Context window check** — `AKIA*` only fires if accompanied by a secret-key-shaped neighbour or "aws" context within 100 characters. +- **Test/example exclusion list** — common dummy values (`AKIAIOSFODNN7EXAMPLE`, `xxx`, `your_key_here`) bypass detection unless `--secrets-strict` is set. + +For a high-stakes audit (e.g. legal disclosure scan), use `--secrets-strict` to disable these guards and accept higher false-positive rate. + +## Configuration + +```yaml +ingestion: + secrets_mask: + enabled: true + tag_by_category: true # use category-specific tags instead of [REDACTED-SECRET] + strict: false # set true to disable false-positive guards + categories: # selectively enable + - aws_access_key + - github_pat + - jwt + - pem_block + # omit any to disable +``` + +## Common pitfalls + +:::warn +**Disabling secrets-mask for "trusted internal" data.** Internal logs are the most common source of credential leaks. The cost of running the masker is essentially zero; the cost of a leaked AWS key in a deployed model is unbounded. +::: + +:::warn +**Custom regex without entropy checks.** The biggest cause of secrets-detection false positives is regex-only patterns matching documentation examples. Always pair regex with entropy or context checks. +::: + +:::tip +For corpora that legitimately contain certificates / tokens (security training datasets, CTF content), use `--skip-secrets` rather than fighting the detector. Document the exception in the audit log so future reviewers see why it was disabled. +::: + +## See also + +- [PII Masking](#/data/pii-masking) — sister feature for personal data. +- [Dataset Audit](#/data/audit) — covers secrets detection in audit-only mode. +- [Document Ingestion](#/data/ingestion) — where secrets-mask is invoked. diff --git a/docs/usermanuals/en/data/synthetic-data.md b/docs/usermanuals/en/data/synthetic-data.md new file mode 100644 index 00000000..d2409a5b --- /dev/null +++ b/docs/usermanuals/en/data/synthetic-data.md @@ -0,0 +1,129 @@ +--- +title: Synthetic Data +description: Teacher-to-student distillation — generate training data from a stronger model. +--- + +# Synthetic Data + +When real data is scarce or expensive, you can synthesise additional training examples by prompting a stronger model and capturing its responses. ForgeLM's synthetic-data pipeline does this with `forgelm --generate-data`. + +## Common use cases + +| Use case | What you generate | +|---|---| +| **Distillation** | Teacher (e.g. GPT-4o) answers; student trains on those answers. | +| **Data augmentation** | Paraphrases or variations of your existing data. | +| **Cold-start** | Synthetic examples from a few seed prompts. | +| **Self-instruct** | Prompts and responses both generated. | + +## Quick example + +```yaml +synthetic: + enabled: true + teacher: + provider: "openai" # or "anthropic", "local" + model: "gpt-4o" + api_key: "${OPENAI_API_KEY}" + seed_prompts: "data/seeds.jsonl" # initial prompts + output: "data/synthetic.jsonl" + num_samples: 5000 + temperature: 0.7 + prompt_template: "default" # or path to custom template + budget_usd: 50.0 # cost ceiling + +training: + trainer: "sft" +datasets: + - path: "data/seeds.jsonl" + - path: "data/synthetic.jsonl" # combine seeds + synthetic +``` + +```shell +$ forgelm --config configs/distill.yaml --generate-data +[2026-04-29 14:01:32] generating from gpt-4o +[2026-04-29 14:01:35] 100/5000 (cost so far: $1.20) +[2026-04-29 14:18:55] 5000/5000 (total cost: $42.30) +✓ wrote 5000 rows to data/synthetic.jsonl +$ forgelm --config configs/distill.yaml # train normally +``` + +## Provider support + +| Provider | Models | Auth env var | +|---|---|---| +| `openai` | gpt-4o, gpt-4o-mini, o1, o3-mini | `OPENAI_API_KEY` | +| `anthropic` | claude-opus-4, claude-sonnet-4, claude-haiku-4 | `ANTHROPIC_API_KEY` | +| `local` | Any HuggingFace causal LM | none — local inference | +| `vllm` | Any model served via vLLM | `VLLM_BASE_URL` | + +For local generation: + +```yaml +synthetic: + teacher: + provider: "local" + model: "Qwen/Qwen2.5-72B-Instruct" + load_in_4bit: true +``` + +## Cost controls + +API-based generation can run up costs quickly. ForgeLM ships hard limits: + +```yaml +synthetic: + budget_usd: 50.0 # hard ceiling — generation halts here + max_tokens_per_response: 1024 # cap response length + rate_limit: + requests_per_minute: 100 # respect provider rate limits + burst: 10 +``` + +When the budget is reached, ForgeLM stops with the partial dataset. The audit log records exactly how much was spent. + +## Quality controls + +Synthetic data is only useful if it's good. ForgeLM's defaults filter: + +- **Empty or single-token responses** — the API failed mid-generation; row dropped. +- **Refusals** — pattern-matches "I can't help with that" and similar; row tagged but kept (you might want to keep refusals for safety training). +- **Format failures** — for structured prompts, validates the output fits. + +## Citation in the model card + +When you train on synthetic data, the auto-generated model card cites the teacher: + +```markdown +## Training data + +This model was trained on: +- 12,000 rows of human-curated data (data/seeds.jsonl) +- 5,000 rows of synthetic data generated by openai:gpt-4o (2026-04-29) +``` + +This matters for licensing and commercial use — distilling some teachers requires acknowledging the source. + +:::warn +**Check the teacher's terms of service.** Some providers (notably OpenAI for some models) restrict using outputs to train competing models. The model-card citation is a *truth-claim*, not a *licence-grant*. Verify your use is permitted. +::: + +## Common pitfalls + +:::warn +**Distilling a teacher into a far smaller student.** A 7B student rarely captures a 405B teacher's capabilities. Realistic ratios: 70B → 7B works (with quality loss); 405B → 1.3B doesn't. +::: + +:::warn +**Self-instruct without quality filter.** Models generating their own training data tend to drift towards safe, generic outputs. Apply LLM-as-judge ([Judge](#/evaluation/judge)) to filter low-quality synthesised rows. +::: + +:::warn +**Forgetting `temperature`.** `temperature=0` produces deterministic responses — the same teacher answer to the same prompt. Use `temperature=0.7` or higher for diversity. +::: + +## See also + +- [LLM-as-Judge](#/evaluation/judge) — filter synthetic data quality. +- [Configuration Reference](#/reference/configuration) — full `synthetic:` block. +- [Document Ingestion](#/data/ingestion) — `--format qa` uses synthetic prompt generation. diff --git a/docs/usermanuals/en/deployment/chat.md b/docs/usermanuals/en/deployment/chat.md new file mode 100644 index 00000000..5bdaca75 --- /dev/null +++ b/docs/usermanuals/en/deployment/chat.md @@ -0,0 +1,140 @@ +--- +title: Interactive Chat +description: Sanity-check your fine-tuned model in a streaming REPL with safety routing. +--- + +# Interactive Chat + +`forgelm chat` opens a streaming REPL against any checkpoint — local, merged, or LoRA-adapter. It's the fastest way to sanity-check that fine-tuning produced the model you wanted. + +## Quick example + +```shell +$ forgelm chat ./checkpoints/customer-support +ForgeLM 0.5.2 — chat with checkpoints/customer-support +forgelm> how do I cancel my subscription? +You can cancel from Settings → Billing → Cancel subscription. Your access +continues until the end of the current billing period… + +forgelm> /system You are a polite customer-support agent for a Turkish telecom. +[system prompt updated] + +forgelm> aboneliği nasıl iptal ederim? +Aboneliğinizi iptal etmek için Ayarlar → Faturalandırma → Aboneliği İptal Et +yolunu izleyebilirsiniz... +``` + +## Slash commands + +| Command | What it does | +|---|---| +| `/reset` | Clear conversation history. | +| `/save ` | Save the conversation to JSONL. | +| `/load ` | Load a previous conversation. | +| `/system ` | Set or update the system prompt. | +| `/temperature ` | Set sampling temperature (0.0 to 2.0). | +| `/top_p ` | Set nucleus sampling parameter. | +| `/max_tokens ` | Cap response length. | +| `/safety on|off` | Toggle Llama Guard pre/post screening. | +| `/help` | Show this list. | +| `/quit` or `Ctrl+D` | Exit. | + +## Configuration + +```yaml +chat: + default_temperature: 0.7 + default_top_p: 0.9 + default_max_tokens: 1024 + default_system_prompt: "You are a helpful assistant." + history_file: "~/.forgelm/chat-history" # persisted across sessions +``` + +## Loading a checkpoint + +`forgelm chat` accepts: + +- A directory with adapter weights (LoRA): `./checkpoints/run/` +- A merged checkpoint directory: `./checkpoints/run/merged/` +- A HuggingFace model ID: `Qwen/Qwen2.5-7B-Instruct` +- A GGUF file: `./model.gguf` (uses llama.cpp under the hood) + +For LoRA checkpoints, you can override the base model: + +```shell +$ forgelm chat ./checkpoints/run/ --base "Qwen/Qwen2.5-7B" +``` + +## Safety routing + +With `--safety on`, every prompt and response is screened by Llama Guard: + +```text +forgelm> [adversarial prompt] +[Llama Guard flagged S2 (non-violent crimes) — refusing] +I can't help with that. Try rephrasing the question. +``` + +Useful when probing the model for jailbreaks before deployment. Off by default for ordinary chat. + +## Multi-turn handling + +Conversation history is preserved within a session. The model sees the full chat (or as much as fits in `max_length`): + +```text +forgelm> what's the capital of Türkiye? +Ankara. + +forgelm> what's its population? +[uses prior context: "its" refers to Ankara] +About 5.7 million as of recent estimates... +``` + +To start fresh: `/reset`. + +## Saving and replaying + +```shell +forgelm> /save sessions/qa-1.jsonl +[saved 6 turns to sessions/qa-1.jsonl] + +forgelm> /load sessions/qa-1.jsonl +[loaded 6 turns; ready to continue] +``` + +Sessions are useful for: +- Reproducing a bug you found during testing. +- Building a benchmark prompt set from interactive exploration. +- Comparing two model versions on the same conversation. + +## Comparing two models + +```shell +$ forgelm chat-compare ./checkpoints/v1 ./checkpoints/v2 --prompts data/probes.jsonl + v1 (helpful) v2 (helpful) judge winner +"How do I cancel..." ✓ "Settings →" ✓ "Settings →" tie +"Reset password?" ✓ "I can help" ✓ "Click 'Forgot'" v2 +"Refund policy?" ✗ vague ✓ specific v2 + ─────── +Win rate v2 vs v1: 0.62 (sig p=0.04) +``` + +## Common pitfalls + +:::warn +**Treating `/temperature 0` as deterministic.** It's near-deterministic, but tiebreaks in argmax sampling can still produce minor variance. For exact reproducibility, set `seed:` in YAML. +::: + +:::warn +**Long conversations exceeding context.** Once history exceeds `max_length`, ForgeLM drops oldest messages first. The conversation can lose continuity unexpectedly. Use `/reset` periodically for long testing sessions. +::: + +:::tip +For automated probing of many prompts, use `forgelm batch-chat --prompts data/probes.jsonl --output responses.jsonl` instead of the interactive REPL. Same model, no manual typing. +::: + +## See also + +- [LLM-as-Judge](#/evaluation/judge) — automate the comparison. +- [Llama Guard Safety](#/evaluation/safety) — same Llama Guard model used here. +- [Deploy Targets](#/deployment/deploy-targets) — once you're happy, deploy. diff --git a/docs/usermanuals/en/deployment/deploy-targets.md b/docs/usermanuals/en/deployment/deploy-targets.md new file mode 100644 index 00000000..f39d3cd0 --- /dev/null +++ b/docs/usermanuals/en/deployment/deploy-targets.md @@ -0,0 +1,215 @@ +--- +title: Deploy Targets +description: Generate Ollama, vLLM, TGI, and HuggingFace Endpoints deployment configs in one command. +--- + +# Deploy Targets + +ForgeLM doesn't ship its own inference server — that's outside scope. Instead, `forgelm deploy` generates ready-to-run configurations for the major existing servers: Ollama, vLLM, TGI, and HuggingFace Endpoints. + +## Quick example + +```shell +$ forgelm deploy ./checkpoints/customer-support \ + --target ollama \ + --output ./Modelfile +✓ wrote ./Modelfile + +$ ollama create my-bot -f ./Modelfile +$ ollama run my-bot +``` + +## Supported targets + +| Target | Output | Use case | +|---|---|---| +| `ollama` | `Modelfile` | Local CPU/GPU inference, fast prototyping. | +| `vllm` | `vllm-config.yaml` | High-throughput GPU serving. | +| `tgi` | `tgi-launcher.sh` + Dockerfile | HuggingFace's text-generation-inference. | +| `hf-endpoints` | `endpoints-config.json` | One-click deploy to HuggingFace Inference Endpoints. | +| `kserve` | `inference-service.yaml` | Kubernetes-native model serving. | +| `triton` | `model_repository/` | NVIDIA Triton Inference Server. | + +## Ollama + +```shell +$ forgelm deploy ./checkpoints/run --target ollama --output Modelfile +``` + +Generates: + +```text +FROM ./model.q4_k_m.gguf + +SYSTEM "You are a polite customer-support agent for telecom." + +PARAMETER temperature 0.7 +PARAMETER top_p 0.9 +PARAMETER stop "<|im_end|>" + +# Generated by ForgeLM 0.5.2 from checkpoint customer-support v1.2.0 +``` + +ForgeLM picks the right `PARAMETER` lines based on the model's tokeniser (chat templates, stop tokens) — no manual configuration needed. + +## vLLM + +```shell +$ forgelm deploy ./checkpoints/run --target vllm --output vllm.yaml +``` + +Generates: + +```yaml +# vllm.yaml — generated by ForgeLM +model: "/data/model" # mount checkpoint at /data/model +tokenizer_mode: "auto" +dtype: "bfloat16" +max_model_len: 8192 +gpu_memory_utilization: 0.85 +trust_remote_code: false +served_model_name: "customer-support-v1.2" + +# Chat template auto-detected from tokeniser +chat_template: null # uses tokenizer's default +``` + +Run: + +```shell +$ python -m vllm.entrypoints.openai.api_server --config vllm.yaml --port 8000 +``` + +For high-throughput, ForgeLM also generates the recommended `--tensor-parallel-size` based on the model size and the configured GPU count. + +## TGI (text-generation-inference) + +```shell +$ forgelm deploy ./checkpoints/run --target tgi --output tgi/ +$ ls tgi/ +launcher.sh Dockerfile config.json +``` + +`launcher.sh`: + +```shell +#!/bin/sh +text-generation-launcher \ + --model-id /data/model \ + --port 8080 \ + --max-input-length 4096 \ + --max-total-tokens 8192 \ + --dtype bfloat16 \ + --quantize bitsandbytes-nf4 +``` + +The `Dockerfile` is multi-stage and pulls TGI's base image — push to your registry and `docker run` it. + +## HuggingFace Endpoints + +```shell +$ forgelm deploy ./checkpoints/run --target hf-endpoints --output endpoints.json +``` + +The output JSON is the body for HuggingFace's Inference Endpoints create-endpoint API: + +```shell +$ curl -X POST https://api.endpoints.huggingface.cloud/v2/endpoint \ + -H "Authorization: Bearer $HF_TOKEN" \ + -H "Content-Type: application/json" \ + -d @endpoints.json +``` + +Or paste into HuggingFace's UI for one-click deployment. + +## KServe (Kubernetes) + +```shell +$ forgelm deploy ./checkpoints/run --target kserve --output kserve.yaml +$ kubectl apply -f kserve.yaml +``` + +Generates a `InferenceService` manifest: + +```yaml +apiVersion: "serving.kserve.io/v1beta1" +kind: "InferenceService" +metadata: + name: customer-support-v1.2 +spec: + predictor: + model: + modelFormat: { name: huggingface } + runtime: kserve-huggingfaceserver + storageUri: "s3://my-models/customer-support-v1.2/" + resources: + limits: + nvidia.com/gpu: 1 +``` + +## Triton Inference Server + +```shell +$ forgelm deploy ./checkpoints/run --target triton --output ./model_repository/ +``` + +Generates the directory structure Triton expects: + +```text +model_repository/ +└── customer-support-v1.2/ + ├── 1/ + │ └── model.savedmodel/ + └── config.pbtxt +``` + +## Configuration + +```yaml +deployment: + target: "vllm" + served_model_name: "customer-support-v1.2" + max_input_length: 4096 + max_total_tokens: 8192 + gpu_memory_utilization: 0.85 + chat_template: "default" # or path to a .jinja file + system_prompt_default: "You are..." +``` + +When `deployment:` is in your YAML, `forgelm` runs `deploy` automatically as the last step (after eval / safety pass). + +## What's auto-detected + +| Setting | Detected from | +|---|---| +| Chat template | Model's tokeniser config | +| Stop tokens | Tokeniser special tokens | +| `max_model_len` | `model.max_length` from training | +| Quantisation | Whether you ran QLoRA, exported GGUF, etc. | +| Tensor parallelism | Model size + available GPUs | + +You can override any auto-detection with explicit YAML. + +## Common pitfalls + +:::warn +**Skipping safety eval on the deployed quant.** A q4_k_m GGUF can score worse on Llama Guard than the full-precision adapter. Re-run safety eval on the deployed artefact, not just the training output. +::: + +:::warn +**Generic chat template fallback.** If your fine-tune used a custom chat template, the auto-detection might pick the base model's template (different format). Test interactively with `forgelm chat` first. +::: + +:::warn +**Stale templates.** When you bump models or tokenisers, regenerate deploy configs. An old TGI config pointing at a new tokeniser silently produces malformed outputs. +::: + +:::tip +ForgeLM's generated configs include a comment with the source run-id and timestamp. Always commit the generated config alongside your model release so traces back are unambiguous. +::: + +## See also + +- [GGUF Export](#/deployment/gguf-export) — for Ollama / llama.cpp targets. +- [Interactive Chat](#/deployment/chat) — test before deploying. +- [Compliance Overview](#/compliance/overview) — what to attach to a release. diff --git a/docs/usermanuals/en/deployment/gguf-export.md b/docs/usermanuals/en/deployment/gguf-export.md new file mode 100644 index 00000000..736cb7d9 --- /dev/null +++ b/docs/usermanuals/en/deployment/gguf-export.md @@ -0,0 +1,148 @@ +--- +title: GGUF Export +description: Quantise to GGUF for local inference with llama.cpp, Ollama, or LM Studio. +--- + +# GGUF Export + +GGUF (GPT-Generated Unified Format) is the de facto file format for local CPU/GPU inference via `llama.cpp`. ForgeLM exports any fine-tuned checkpoint to GGUF with six quantisation levels and a SHA-256 manifest. + +## Quick example + +```shell +$ forgelm export ./checkpoints/customer-support \ + --output model.gguf \ + --quant q4_k_m +✓ merged LoRA into base +✓ converted to GGUF +✓ quantised to q4_k_m (4.1 GB → 4.1 GB) +✓ wrote model.gguf and model.gguf.sha256 +``` + +The output is a single `.gguf` file plus a `.sha256` manifest. + +## Quantisation levels + +| Level | Size (7B base) | Quality | Use case | +|---|---|---|---| +| `q8_0` | 7.2 GB | Highest | Quality benchmark; production where memory is plentiful. | +| `q6_k` | 5.5 GB | Very high | Default for production. | +| `q5_k_m` | 4.8 GB | High | Sensible balance. | +| `q4_k_m` | 4.1 GB | Good | **Default for local inference.** | +| `q3_k_m` | 3.3 GB | Acceptable | Tight memory; some quality loss. | +| `q2_k` | 2.6 GB | Lower | Last-resort for edge devices; noticeable quality loss. | + +`q4_k_m` is the sweet spot — fits easily on consumer hardware, minimal quality loss versus full precision. + +## Configuration + +```yaml +output: + gguf: + enabled: true # auto-export after training + quant_levels: ["q4_k_m", "q5_k_m"] # export multiple levels in one go + output_dir: "${output.dir}/gguf/" + manifest: true +``` + +When `enabled: true`, ForgeLM exports automatically as part of `forgelm` runs that pass eval. When false (default), use `forgelm export` ad hoc. + +## Multi-quant export + +```shell +$ forgelm export ./checkpoints/run \ + --output ./gguf/ \ + --quant "q4_k_m,q5_k_m,q8_0" +✓ wrote gguf/model.q4_k_m.gguf (4.1 GB) +✓ wrote gguf/model.q5_k_m.gguf (4.8 GB) +✓ wrote gguf/model.q8_0.gguf (7.2 GB) +✓ wrote gguf/manifest.json +``` + +The manifest: + +```json +{ + "base_model": "Qwen/Qwen2.5-7B-Instruct", + "fine_tune_run_id": "abc123", + "quants": { + "q4_k_m": {"size_bytes": 4100000000, "sha256": "..."}, + "q5_k_m": {"size_bytes": 4800000000, "sha256": "..."}, + "q8_0": {"size_bytes": 7200000000, "sha256": "..."} + }, + "exported_at": "2026-04-29T15:00:00Z" +} +``` + +## Verifying GGUF integrity + +```shell +$ forgelm verify-gguf model.q4_k_m.gguf +✓ valid GGUF magic +✓ vocab size matches base +✓ sha256 matches manifest +✓ tokenizer round-trip OK +``` + +This catches corruption from bad transfers, silent disk errors, and the occasional `llama.cpp` upstream incompatibility. + +## Loading GGUF in popular tools + +### Ollama + +```shell +$ cat > Modelfile <<'EOF' +FROM ./model.q4_k_m.gguf +SYSTEM "You are a polite customer-support agent." +PARAMETER temperature 0.7 +EOF +$ ollama create my-bot -f Modelfile +$ ollama run my-bot +``` + +### LM Studio + +Drop the `.gguf` file into LM Studio's models directory; it appears in the picker. + +### llama.cpp directly + +```shell +$ ./main -m model.q4_k_m.gguf -p "Hello, how are you?" -n 256 +``` + +## Direct conversion (no quantisation) + +For the rare case where you want fp16 GGUF (e.g. for a quantisation-sensitive inference engine): + +```shell +$ forgelm export ./checkpoints/run --output model.gguf --quant fp16 +``` + +The result is full-precision GGUF, ~14 GB for a 7B model. + +## Common pitfalls + +:::warn +**Exporting LoRA without merging.** `forgelm export` always merges LoRA adapters into the base before quantising. If you want adapter-only inference, you don't want GGUF — use `forgelm chat` against the adapter directly or load with PEFT. +::: + +:::warn +**Tokeniser version mismatch.** GGUF embeds the tokeniser. If you change tokenisers post-training (rare), the GGUF won't load correctly in `llama.cpp`. Always export from the same checkpoint that was actually trained. +::: + +:::warn +**Quality regression vs original.** Aggressive quants (q3, q2) can shift Llama Guard scores. Always re-run safety eval on the GGUF if it's going into production: +```shell +$ forgelm safety-eval --model model.q4_k_m.gguf --probes data/safety-probes.jsonl +``` +::: + +:::tip +For HuggingFace Hub upload, ForgeLM's model card includes a "Use with Ollama" snippet referencing your GGUF file — copy-paste-ready. +::: + +## See also + +- [Deploy Targets](#/deployment/deploy-targets) — non-GGUF deployment options. +- [Configuration Reference](#/reference/configuration) — `output.gguf` block. +- [Model Merging](#/deployment/model-merging) — combining adapters before export. diff --git a/docs/usermanuals/en/deployment/model-merging.md b/docs/usermanuals/en/deployment/model-merging.md new file mode 100644 index 00000000..beec98a5 --- /dev/null +++ b/docs/usermanuals/en/deployment/model-merging.md @@ -0,0 +1,179 @@ +--- +title: Model Merging +description: Combine multiple LoRA adapters into one model with TIES, DARE, SLERP, or linear merge. +--- + +# Model Merging + +Model merging combines several fine-tuned models (or LoRA adapters) into one. Useful when you have specialists (one for code, one for support, one for math) and want a generalist that retains some capability of each. ForgeLM supports four merge algorithms via `forgelm --merge`. + +## When to use merging + +| Use merging when... | Don't use merging when... | +|---|---| +| You have multiple LoRA adapters trained on overlapping bases. | The "specialists" are radically different (different bases, different sizes). | +| You want one deployable model instead of multiple. | You need different behaviours per request — route at inference instead. | +| You're exploring multi-skill models without training from scratch. | Production reliability matters more than capability breadth. | + +Merging trades a bit of each specialist's quality for breadth. Always re-evaluate after merging. + +## Algorithm choice + +| Algorithm | What it does | When it shines | +|---|---|---| +| **Linear** | Average weights with configurable per-adapter coefficients. | Same-architecture, well-aligned adapters. Simplest. | +| **SLERP** | Spherical linear interpolation between two adapters. | Two-way merges; preserves manifold geometry. | +| **TIES** | Trim, Elect-sign, Disjoint-merge. Drops near-zero deltas, resolves conflicts by sign. | 3+ adapters; common starting point. | +| **DARE** | Drop-and-Rescale. Randomly zeroes weight deltas, rescales survivors. | Mitigates interference; pairs well with TIES (DARE-TIES). | + +## Quick example: TIES + +```yaml +merge: + enabled: true + algorithm: "ties" + base_model: "Qwen/Qwen2.5-7B-Instruct" + models: + - path: "./checkpoints/customer-support" + weight: 0.5 + - path: "./checkpoints/code-assistant" + weight: 0.3 + - path: "./checkpoints/math-reasoning" + weight: 0.2 + parameters: + threshold: 0.7 # TIES-specific: top-K% of deltas to keep + output: + dir: "./checkpoints/merged" + model_card: true +``` + +```shell +$ forgelm --merge --config configs/merge.yaml +✓ loaded 3 adapters +✓ TIES merge: kept top 70% of deltas, resolved 1247 sign conflicts +✓ wrote ./checkpoints/merged +✓ generated model card +``` + +## Quick example: Linear + +```yaml +merge: + enabled: true + algorithm: "linear" + base_model: "Qwen/Qwen2.5-7B-Instruct" + models: + - { path: "./checkpoints/v1", weight: 0.5 } + - { path: "./checkpoints/v2", weight: 0.5 } + output: + dir: "./checkpoints/v1-v2-blend" +``` + +Linear is the simplest — just averages weights. Always works as a starting point; might not be optimal. + +## Algorithm parameters + +| Algorithm | Key parameters | +|---|---| +| `linear` | `weights:` per model | +| `slerp` | `t:` interpolation factor (0.0 = first adapter, 1.0 = second) | +| `ties` | `threshold:` (top-K% of deltas to keep, 0.6-0.8 typical), `density:` (alternative formulation) | +| `dare` | `density:` (fraction to keep, 0.5-0.9), `epsilon:` (rescaling) | +| `dare_ties` | Both DARE and TIES parameters | + +## Evaluating after merging + +Always re-evaluate the merged model — it's a different model than any of the inputs. + +```yaml +merge: + enabled: true + algorithm: "ties" + ... + evaluation: + benchmark: + tasks: ["hellaswag", "humaneval", "gsm8k"] # mix of skills from each specialist + floors: + hellaswag: 0.55 + humaneval: 0.40 + gsm8k: 0.50 + safety: + enabled: true +``` + +If the merged model regresses on any task, fall back to one of the specialists or try a different algorithm. + +## Diagnosing merge failures + +Symptoms of a bad merge: + +| Symptom | Likely cause | Fix | +|---|---|---| +| Coherent but generic outputs | Linear merge averaged out specialisations | Try TIES with `threshold: 0.7` | +| Garbled outputs | Adapter base mismatch | Check all adapters use the same base model | +| Random low scores on every task | DARE density too low | Raise `density:` to 0.9 | +| One specialist dominates | Linear weight too high for that adapter | Rebalance weights | + +## Configuration + +```yaml +merge: + enabled: true + algorithm: "ties" + base_model: "Qwen/Qwen2.5-7B-Instruct" + models: + - path: "./checkpoints/v1" + weight: 0.4 + - path: "./checkpoints/v2" + weight: 0.6 + parameters: + threshold: 0.7 + normalize: true # normalise weights to sum to 1.0 + output: + dir: "./checkpoints/merged" + model_card: true + save_format: "safetensors" # or pytorch +``` + +## Programmatic merging + +For automation pipelines: + +```python +from forgelm.merging import merge_adapters + +merge_adapters( + base="Qwen/Qwen2.5-7B-Instruct", + adapters=[ + ("./checkpoints/v1", 0.5), + ("./checkpoints/v2", 0.5), + ], + algorithm="ties", + threshold=0.7, + output_dir="./checkpoints/merged", +) +``` + +## Common pitfalls + +:::warn +**Merging across different bases.** Adapters trained on Qwen2.5-7B can't be merged with adapters trained on Llama-3-8B — different parameter shapes. ForgeLM rejects this at merge time with a clear error. +::: + +:::warn +**Skipping eval on the merged model.** Treating "we merged 3 specialists" as a guarantee of "we have a generalist" is wishful thinking. Re-evaluate. +::: + +:::warn +**Compounding merges.** Merging A+B, then merging the result with C, is generally worse than merging A+B+C in one shot. Use a single multi-way merge. +::: + +:::tip +For exploratory merging, generate a small grid of `(algorithm, parameters)` combinations and evaluate each. ForgeLM ships a `forgelm merge-sweep` helper that automates this. +::: + +## See also + +- [LoRA, QLoRA, DoRA](#/training/lora) — produces the adapters that get merged. +- [Configuration Reference](#/reference/configuration) — full `merge:` block. +- [Synthetic Data](#/data/synthetic-data) — alternative to merging for capability breadth. diff --git a/docs/usermanuals/en/evaluation/auto-revert.md b/docs/usermanuals/en/evaluation/auto-revert.md new file mode 100644 index 00000000..7be20494 --- /dev/null +++ b/docs/usermanuals/en/evaluation/auto-revert.md @@ -0,0 +1,142 @@ +--- +title: Auto-Revert +description: Roll back to the last-good checkpoint when benchmarks or safety regress. +--- + +# Auto-Revert + +A fine-tuned model that scores worse than its starting point on safety or quality is worse than no fine-tune. Auto-revert is ForgeLM's safety net: if any configured threshold fails after training, the run rolls back to the last-good checkpoint and emits a structured incident record. + +## Decision flow + +```mermaid +flowchart TD + Start[Training complete] + Bench{Benchmark
floors pass?} + Safety{Safety
thresholds pass?} + Loss{Final loss
vs starting?} + OK([Promote new checkpoint
exit 0]) + Revert([Restore last-good
exit 3]) + Audit[Append incident
to audit log] + + Start --> Bench + Bench -->|fail| Audit + Bench -->|pass| Safety + Safety -->|fail| Audit + Safety -->|pass| Loss + Loss -->|reasonable| OK + Loss -->|exploded| Audit + Audit --> Revert + + classDef ok fill:#1c2030,stroke:#22c55e,color:#e6e7ec + classDef fail fill:#1c2030,stroke:#ef4444,color:#e6e7ec + classDef question fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + class OK ok + class Revert,Audit fail + class Bench,Safety,Loss question +``` + +## What triggers a revert + +| Signal | Threshold | Configurable via | +|---|---|---| +| Benchmark task below floor | Per-task `floors:` setting | `evaluation.benchmark.floors` | +| Safety regression in blocked category | `regression_tolerance` (default 0.05) | `evaluation.safety.regression_tolerance` | +| Final loss > starting loss | Always | not configurable | +| Final loss is NaN/Inf | Always | not configurable | +| Custom guard fails | User-supplied callable | `evaluation.guards.` | + +Any of these triggers a revert. + +## What happens during a revert + +1. ForgeLM identifies the last-good checkpoint — typically the SFT checkpoint when DPO failed, or the previous training run's output for a continued-training scenario. +2. Copies the last-good weights to the configured output directory (overwriting the bad ones). +3. Writes an incident record to `audit_log.jsonl`: + +```json +{ + "ts": "2026-04-29T14:33:04Z", + "event": "auto_revert", + "trigger": "safety_regression", + "regressed_categories": ["S5"], + "baseline_safety": {"S5": {"max": 0.08}}, + "post_train_safety": {"S5": {"max": 0.42}}, + "restored_from": "./checkpoints/sft-base", + "exit_code": 3 +} +``` + +4. Optionally fires a webhook (Slack, Teams) — see [Webhooks](#/operations/webhooks). +5. Exits with code 3. + +## Configuration + +```yaml +evaluation: + auto_revert: + enabled: true + last_good_checkpoint: "./checkpoints/sft-base" + notify_on_revert: true # fire webhook + keep_failed_checkpoint: true # also keep the bad one for inspection + failed_checkpoint_dir: "./checkpoints/failed/" +``` + +If `last_good_checkpoint` is omitted, ForgeLM uses the model loaded at run start (the input model). + +## Custom guards + +You can register additional guards beyond the built-ins: + +```yaml +evaluation: + guards: + custom_metric: + function: "my_module.check_brand_voice" + threshold: 0.7 # function must return ≥ this + severity: "critical" +``` + +```python +# my_module.py +def check_brand_voice(checkpoint_path: str) -> float: + """Return a brand-voice score in [0, 1].""" + # Run your custom eval... + return 0.82 +``` + +Custom guards integrate into the same revert flow. + +## CI/CD integration + +Auto-revert pairs naturally with CI exit codes: + +```yaml +# .github/workflows/train.yml +- name: Train and evaluate + run: forgelm --config configs/run.yaml + # exit 0 = success, exit 3 = auto-revert triggered +``` + +CI failures from exit 3 are *expected* — they mean the gate caught a regression. Don't suppress them; investigate. + +## Common pitfalls + +:::warn +**Disabling auto-revert "to ship today".** Almost always the wrong call. If you really need to ship, set the floor lower for one run with a clear comment and a follow-up issue. The audit log will record the override. +::: + +:::warn +**`last_good_checkpoint` pointing at a deleted path.** Auto-revert fails noisily if it can't find the restore target. Pin the last-good checkpoint at a stable path before kicking off training. +::: + +:::tip +**Test auto-revert by sabotaging.** During CI setup, intentionally lower a floor to a value you know your model will fail. Confirm auto-revert fires, the webhook posts, and the incident record is written. Better to discover problems with the safety net while you're testing it than during a real regression. +::: + +## See also + +- [Benchmark Integration](#/evaluation/benchmarks) — defines floor thresholds. +- [Llama Guard Safety](#/evaluation/safety) — defines safety thresholds. +- [Webhooks](#/operations/webhooks) — notify on revert. +- [Audit Log](#/compliance/audit-log) — where revert events get recorded. diff --git a/docs/usermanuals/en/evaluation/benchmarks.md b/docs/usermanuals/en/evaluation/benchmarks.md new file mode 100644 index 00000000..7703920e --- /dev/null +++ b/docs/usermanuals/en/evaluation/benchmarks.md @@ -0,0 +1,149 @@ +--- +title: Benchmark Integration +description: Run lm-evaluation-harness tasks with per-task floor thresholds and auto-revert. +--- + +# Benchmark Integration + +ForgeLM integrates with [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) — the standard benchmark suite for LLMs — and adds the production layer on top: per-task floor thresholds, auto-revert on regression, and structured artifacts that flow into your compliance bundle. + +## Quick example + +```yaml +evaluation: + benchmark: + enabled: true + tasks: ["hellaswag", "arc_easy", "truthfulqa", "mmlu"] + floors: + hellaswag: 0.55 + arc_easy: 0.70 + truthfulqa: 0.45 + num_fewshot: 0 # zero-shot eval + batch_size: 8 + output_dir: "./checkpoints/run/artifacts/" +``` + +After training, ForgeLM runs the listed tasks, compares to floors, and: +- All tasks pass floor → run succeeds (exit 0) +- Any task drops below floor → auto-revert to last-good checkpoint, exit 3 + +## Supported tasks + +Anything in `lm-evaluation-harness` works. Common picks: + +| Task | What it measures | +|---|---| +| `hellaswag` | Commonsense completion | +| `arc_easy`, `arc_challenge` | Grade-school science | +| `truthfulqa` | Resistance to common misconceptions | +| `mmlu` | Broad multitask knowledge | +| `winogrande` | Pronoun resolution | +| `gsm8k` | Grade-school math (chain of thought) | +| `humaneval` | Code completion | + +For Turkish projects, ForgeLM ships templates for `mmlu_tr` and `belebele_tr` adapted to Turkish-specific tasks. + +## Per-task floors + +Floors define the minimum acceptable post-training score per task. The model isn't promoted until *every* task passes its floor. + +```yaml +evaluation: + benchmark: + floors: + hellaswag: 0.55 + mmlu: 0.50 + # tasks without floors are reported but don't block promotion + truthfulqa: 0.45 +``` + +A floor of `null` means "report but don't gate". A floor of `0` is the same as no floor (everything passes). + +:::tip +Set floors slightly below your pre-training baseline. Goal: catch *regressions*, not require improvement on every task. A model that gains 5% on the target task while losing 2% on hellaswag is usually fine; one that drops 15% on hellaswag is broken. +::: + +## Pre-train baselines + +To know what floor to set, you need a pre-training baseline: + +```shell +$ forgelm benchmark --model "Qwen/Qwen2.5-7B-Instruct" \ + --tasks hellaswag,arc_easy,truthfulqa,mmlu \ + --output baselines/qwen-2.5-7b.json +{"hellaswag": 0.61, "arc_easy": 0.75, "truthfulqa": 0.49, "mmlu": 0.52} +``` + +A reasonable floor is the baseline minus 0.03 (3% slack for stochastic variation): + +```yaml +evaluation: + benchmark: + floors: + hellaswag: 0.58 # baseline 0.61 - 0.03 + arc_easy: 0.72 + truthfulqa: 0.46 + mmlu: 0.49 +``` + +## Output artifacts + +After eval, ForgeLM writes: + +```text +checkpoints/run/artifacts/ +├── benchmark_results.json ← per-task scores + floor verdicts +└── benchmark_run.log ← full lm-eval-harness output +``` + +`benchmark_results.json` structure: + +```json +{ + "tasks": { + "hellaswag": { + "score": 0.617, "floor": 0.55, "passed": true, + "fewshot": 0, "n": 10042 + }, + "truthfulqa": { + "score": 0.42, "floor": 0.45, "passed": false + } + }, + "verdict": "regression", + "regressed_tasks": ["truthfulqa"] +} +``` + +CI pipelines parse `verdict`. See [Auto-Revert](#/evaluation/auto-revert) for the gating logic. + +## Configuration parameters + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `enabled` | bool | `false` | Master switch. | +| `tasks` | list | `[]` | Task names from lm-eval-harness. | +| `floors` | dict | `{}` | Per-task minimum acceptable score. | +| `num_fewshot` | int | `0` | 0 for zero-shot, 5 for 5-shot. | +| `batch_size` | int | `8` | Eval batch size. | +| `limit` | int | `null` | Cap rows per task — for fast smoke tests. | +| `device` | string | `"cuda:0"` | Eval device. | + +## Common pitfalls + +:::warn +**Floors above pre-train baseline.** Set the floor higher than what the base model achieves and *every* run fails — auto-revert kicks in and you never get a checkpoint. Always start with `baseline - margin`. +::: + +:::warn +**`num_fewshot` mismatch with reported public results.** Public leaderboards report at specific shot counts (e.g. MMLU is canonically 5-shot). Use the same setting if you want results to be comparable. +::: + +:::tip +**Speed up iteration with `limit`.** Setting `limit: 100` runs 100 rows per task (instead of thousands) for ~10× faster eval. Use this in dev configs; remove for production. +::: + +## See also + +- [Auto-Revert](#/evaluation/auto-revert) — what happens when floors fail. +- [LLM-as-Judge](#/evaluation/judge) — qualitative eval beyond benchmarks. +- [Trend Tracking](#/evaluation/trend-tracking) — comparing scores across runs. diff --git a/docs/usermanuals/en/evaluation/judge.md b/docs/usermanuals/en/evaluation/judge.md new file mode 100644 index 00000000..ba80cff8 --- /dev/null +++ b/docs/usermanuals/en/evaluation/judge.md @@ -0,0 +1,167 @@ +--- +title: LLM-as-Judge +description: Quality scoring with OpenAI or a local judge model — pairwise, single-rubric, or ELO-style. +--- + +# LLM-as-Judge + +Standard benchmarks measure narrow capabilities; they don't capture "is this response actually good?". LLM-as-judge fills that gap by using a stronger model to evaluate yours. ForgeLM supports three modes: pairwise comparison, single-rubric scoring, and ELO-style ranking. + +## When to use + +| Use LLM-as-judge when... | Use benchmarks when... | +|---|---| +| Output quality is subjective (helpful, polite, on-brand). | The task has a verifiable answer. | +| You don't have ground truth. | You have ground truth. | +| You're comparing two models' qualitative output. | You're tracking absolute performance over time. | +| Cost is acceptable (~$1-5 per 1K judgements with GPT-4o). | You need free, local eval. | + +## Quick example + +```yaml +evaluation: + judge: + enabled: true + mode: "pairwise" # or single-rubric, elo + judge_model: + provider: "openai" + model: "gpt-4o-mini" # cheaper than gpt-4o, almost as good for judging + api_key: "${OPENAI_API_KEY}" + baseline_model: "./checkpoints/sft-base" + test_prompts: "data/eval-prompts.jsonl" + num_samples: 200 + rubric: "default" # or path to custom rubric +``` + +## Pairwise mode + +Asks the judge: "Response A or Response B — which is better, and why?" Aggregates win-rates. + +```json +{ + "pairwise_results": { + "wins": 124, + "losses": 56, + "ties": 20, + "win_rate": 0.62, + "judge_explanations_sample": [...] + } +} +``` + +A win rate above 0.55 with 200+ samples is statistically meaningful. Below that, run more samples or accept that the differences are noise. + +## Single-rubric mode + +Asks the judge to score each response on a rubric (1-5 stars per criterion). + +```yaml +evaluation: + judge: + mode: "single-rubric" + rubric: + criteria: + - name: "helpfulness" + description: "Does the response solve the user's problem?" + scale: 5 + - name: "tone" + description: "Is the tone appropriate for customer support?" + scale: 5 + - name: "factual_accuracy" + description: "Are claims correct?" + scale: 5 +``` + +Output: + +```json +{ + "rubric_means": { + "helpfulness": 4.2, + "tone": 4.7, + "factual_accuracy": 3.8 + }, + "rubric_distributions": {...} +} +``` + +## ELO mode + +Runs round-robin pairwise comparisons across multiple model versions, computes ELO ratings. + +```yaml +evaluation: + judge: + mode: "elo" + candidates: + - name: "v1" + path: "./checkpoints/v1" + - name: "v2" + path: "./checkpoints/v2" + - name: "v3-current" + path: "./checkpoints/v3" + rounds: 50 +``` + +Output: ELO ratings per candidate. Useful when comparing across many runs (e.g. hyperparameter sweep). + +## Judge model choice + +| Judge | Cost / 1K judgements | Quality | +|---|---|---| +| `openai:gpt-4o` | ~$5 | Highest. Default for production. | +| `openai:gpt-4o-mini` | ~$1 | 90% of gpt-4o quality. Recommended. | +| `anthropic:claude-haiku-4` | ~$1.50 | Comparable to gpt-4o-mini. | +| `local:Qwen2.5-72B-Instruct` | $0 (your GPU time) | Reasonable; weaker on subtle judgement calls. | +| `local:Llama-3.1-70B-Instruct` | $0 | Slightly worse than Qwen 72B for judging. | + +## Reducing variance + +Single judge runs are noisy. ForgeLM ships standard variance-reduction: + +- **Self-consistency** — `--num-judgements 3` runs each comparison three times, takes majority. +- **Position swap** — alternates which response is "A" vs "B" to detect position bias. +- **Multiple rubrics** — averages across criteria. + +```yaml +evaluation: + judge: + self_consistency: 3 # 3 votes per comparison + swap_positions: true # detect position bias +``` + +## Cost controls + +```yaml +evaluation: + judge: + budget_usd: 20.0 # halt at $20 + rate_limit: + requests_per_minute: 60 +``` + +When the budget is hit, judge halts with partial results. + +## Common pitfalls + +:::warn +**Using the same model as judge and student.** A 7B model judging another 7B's outputs won't catch subtle quality issues. Use a stronger judge. +::: + +:::warn +**Position bias.** Judges often prefer the first response slightly. Always set `swap_positions: true` for pairwise comparisons. +::: + +:::warn +**Tiny sample sizes.** Comparing two models with 20 prompts is statistical noise. Use 200+ for meaningful win-rates. +::: + +:::tip +**Pair judge with benchmarks.** A model that wins on judge but regresses on benchmarks is overfitting to whatever the judge prefers. Both signals matter. +::: + +## See also + +- [Benchmark Integration](#/evaluation/benchmarks) — quantitative eval companion. +- [Synthetic Data](#/data/synthetic-data) — same provider abstraction. +- [Auto-Revert](#/evaluation/auto-revert) — judge can be a gating signal. diff --git a/docs/usermanuals/en/evaluation/safety.md b/docs/usermanuals/en/evaluation/safety.md new file mode 100644 index 00000000..6640c191 --- /dev/null +++ b/docs/usermanuals/en/evaluation/safety.md @@ -0,0 +1,151 @@ +--- +title: Llama Guard Safety +description: Confidence-weighted safety scoring across 14 harm categories with auto-revert. +--- + +# Llama Guard Safety + +Llama Guard is Meta's family of safety-classifier models. ForgeLM wraps Llama Guard with confidence-weighted scoring, severity tiers, and trend tracking — turning a raw classifier into a production gate. + +## Quick example + +```yaml +evaluation: + safety: + enabled: true + model: "meta-llama/Llama-Guard-3-8B" + block_categories: ["S1", "S2", "S5", "S10"] + test_prompts: "data/safety-probes.jsonl" + severity_threshold: "high" + output_dir: "./checkpoints/run/artifacts/" +``` + +After each training run, ForgeLM: +1. Generates responses to a held-out set of safety probe prompts. +2. Scores each response across the 14 Llama Guard categories. +3. Compares to the pre-train baseline and the configured thresholds. +4. Triggers auto-revert if blocked categories regress beyond tolerance. + +## Harm categories (S1–S14) + +| Category | Description | +|---|---| +| **S1** | Violent crimes | +| **S2** | Non-violent crimes | +| **S3** | Sex crimes | +| **S4** | Child exploitation | +| **S5** | Defamation | +| **S6** | Specialised advice (legal, medical, financial — when not authorised) | +| **S7** | Privacy violations | +| **S8** | Intellectual property | +| **S9** | Indiscriminate weapons | +| **S10** | Hate speech | +| **S11** | Self-harm | +| **S12** | Sexual content | +| **S13** | Elections / disinformation | +| **S14** | Code interpreter abuse | + +`block_categories` is the list of categories the model must NOT regress on. Other categories are scored and reported but don't trigger gating. + +## Severity tiers + +ForgeLM groups Llama Guard's per-category outputs into severity tiers: + +| Tier | Confidence range | Action | +|---|---|---| +| `clean` | All categories below 0.10 | Pass | +| `low` | One or more categories 0.10-0.30 | Warn but pass | +| `medium` | One or more categories 0.30-0.60 | Pass with logging if not in block list; auto-revert if in block list | +| `high` | Any category > 0.60 | Auto-revert | +| `critical` | Any blocked category > 0.85 | Auto-revert + structured incident | + +`severity_threshold` controls the strictness: + +| Setting | Triggers auto-revert at | +|---|---| +| `low` | Any flag in blocked category | +| `medium` (default) | Confidence > 0.30 in blocked category | +| `high` | Confidence > 0.60 in blocked category | +| `critical` | Confidence > 0.85 in blocked category | + +## Pre-train baseline + +Before relying on Llama Guard as a gate, score your *base* model: + +```shell +$ forgelm safety-eval --model "Qwen/Qwen2.5-7B-Instruct" \ + --probes data/safety-probes.jsonl \ + --output baselines/safety-qwen-7b.json +``` + +This becomes the comparison point — auto-revert fires when a fine-tune *regresses* below baseline, not when the absolute score is bad. Fine-tuning rarely improves safety; the goal is to not make it worse. + +## Test prompt design + +The probe set should be: + +- **Representative** of the deployed surface (customer-support, code, etc.). +- **Adversarial** — include known jailbreak patterns and category-specific probes. +- **Categorised** — each probe tagged with the category it targets. + +ForgeLM ships a default 200-prompt probe set as part of `forgelm safety-eval --default-probes`. Augment with your own. + +## Output artifacts + +```text +checkpoints/run/artifacts/ +├── safety_report.json ← per-category confidence scores +├── safety_examples.jsonl ← top 10 worst-flagged responses (for review) +└── safety_run.log ← full Llama Guard outputs +``` + +`safety_report.json`: + +```json +{ + "model": "meta-llama/Llama-Guard-3-8B", + "categories": { + "S1": {"max": 0.04, "mean": 0.01, "regressed": false}, + "S5": {"max": 0.42, "mean": 0.08, "regressed": true}, + ... + }, + "verdict": "regression", + "regressed_blocked_categories": ["S5"] +} +``` + +## Configuration parameters + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `enabled` | bool | `false` | Master switch. | +| `model` | string | `"meta-llama/Llama-Guard-3-8B"` | Llama Guard variant. | +| `block_categories` | list | `[]` | Categories the model must not regress on. | +| `test_prompts` | string | (built-in) | Path to JSONL probe set. | +| `severity_threshold` | string | `"medium"` | Strictness — see severity tiers. | +| `regression_tolerance` | float | `0.05` | Max allowed regression vs baseline (5%). | +| `baseline` | string | `null` | Path to pre-train baseline JSON. | + +## Common pitfalls + +:::warn +**Setting `block_categories` to "all 14".** The model will regress on something — usually S5 (defamation) or S6 (specialised advice). Block what matters for your deployment, not everything. +::: + +:::warn +**Probe set too small.** Fewer than 100 probes per blocked category produces unstable scores. Use the built-in 200-prompt set as a minimum. +::: + +:::warn +**Llama Guard memory.** Llama Guard 3 8B needs ~16 GB on its own. If your training already maxes out VRAM, run safety eval as a separate stage rather than in the same process. +::: + +:::tip +**Track Llama Guard verdicts over time.** A category that's been creeping up over several runs is more important than a one-off spike. See [Trend Tracking](#/evaluation/trend-tracking). +::: + +## See also + +- [Auto-Revert](#/evaluation/auto-revert) — what happens when safety regresses. +- [Trend Tracking](#/evaluation/trend-tracking) — long-term safety trends. +- [Compliance Overview](#/compliance/overview) — how safety reports flow into the audit bundle. diff --git a/docs/usermanuals/en/evaluation/trend-tracking.md b/docs/usermanuals/en/evaluation/trend-tracking.md new file mode 100644 index 00000000..ff5a230e --- /dev/null +++ b/docs/usermanuals/en/evaluation/trend-tracking.md @@ -0,0 +1,130 @@ +--- +title: Trend Tracking +description: Compare evaluation results across runs to spot slow drifts before they cross thresholds. +--- + +# Trend Tracking + +Per-run thresholds catch regressions; trend tracking catches drift. A category that's been creeping up over five runs is a different (and often more important) signal than a one-off spike. ForgeLM stores eval results in a per-project history file and reports trends every time you run. + +## Quick example + +After several runs of the same project, the audit report includes a trend section: + +```json +{ + "trend": { + "lookback_runs": 10, + "benchmark": { + "hellaswag": {"trend": "stable", "delta_per_run": 0.001}, + "truthfulqa": {"trend": "drifting_down", "delta_per_run": -0.012, "concern": "medium"} + }, + "safety": { + "S5": {"trend": "drifting_up", "delta_per_run": 0.04, "concern": "high"}, + "S10": {"trend": "stable", "delta_per_run": 0.001} + } + } +} +``` + +The `concern` levels: + +| Level | Trigger | +|---|---| +| `none` | No drift detected over lookback window. | +| `low` | Drift trend statistically present but small. | +| `medium` | Steady drift; will hit threshold within ~10 runs at current rate. | +| `high` | Steady drift; will hit threshold within ~3 runs. | +| `critical` | Already at or near threshold AND drifting. | + +## How drift is computed + +For each metric (benchmark task or safety category): + +1. Pull the last N runs from the project history. +2. Linear-regress the score on run index. +3. Test slope against zero with a t-test. +4. If slope is significant *and* its magnitude is over the noise floor, report drift. + +`lookback_runs` defaults to 10 — adjust based on how often you train. + +## Configuration + +```yaml +evaluation: + trend: + enabled: true + history_file: "./.forgelm/eval-history.jsonl" + lookback_runs: 10 + drift_p_threshold: 0.05 # statistical significance + fail_on_concern: "high" # exit 3 if any drift hits 'high' +``` + +`fail_on_concern: high` upgrades trend tracking from "advisory" to "gating" — your CI will fail not just on per-run regressions but also on drifts headed for trouble. + +## Where the history file lives + +By default, `.forgelm/eval-history.jsonl` in the project root. Each run appends one row: + +```json +{"ts": "2026-04-29T14:33:04Z", "run_id": "abc123", "config_hash": "deadbeef", "benchmark": {...}, "safety": {...}} +``` + +Commit this file. It's small (one row per run, JSON), and it's the only way to track trends across CI runs and contributors. + +## Visualisation + +ForgeLM ships a CLI report: + +```shell +$ forgelm trend --metric "safety.S5" --lookback 20 + +S5 (defamation) — last 20 runs: + + 0.42 ┤ ╭────● + 0.30 ┤ ╭─────╯ + 0.18 ┤ ╭───────────╯ + 0.06 ┤ ●─────●─────●─────●────────╯ + └─┴───────────────────────────────────────────────────┘ + 1 3 5 7 9 11 13 15 17 19 20 + +Linear fit: slope=+0.018/run, p=0.001 — drifting up (high concern) +``` + +For dashboards, the JSONL is easy to load into Grafana or Datadog: + +```shell +$ jq '.benchmark.truthfulqa, .ts' .forgelm/eval-history.jsonl > truthfulqa-trend.csv +``` + +## Run identification + +Each run has a `run_id` (UUID) and a `config_hash` (hash of the YAML config). When you compare runs, compare like-for-like — a hyperparameter change can shift baselines without that being a regression. + +Filter the history: + +```shell +$ forgelm trend --metric "benchmark.hellaswag" \ + --filter "config_hash=deadbeef" \ + --lookback 30 +``` + +## Common pitfalls + +:::warn +**Mixing config-changed runs with config-stable runs.** A trend computed across runs with different configs is meaningless. Use `--filter config_hash` for like-for-like. +::: + +:::warn +**Lookback too short.** With `lookback_runs: 3`, every random fluctuation looks like drift. Stay at 10+ for stable signal. +::: + +:::tip +**Annotate the history.** When you intentionally change something (new dataset, new hyperparameters), commit a note to `.forgelm/eval-history.jsonl` explaining why baselines might shift. Future you will thank past you. +::: + +## See also + +- [Benchmark Integration](#/evaluation/benchmarks) — produces the data. +- [Llama Guard Safety](#/evaluation/safety) — produces safety scores. +- [Auto-Revert](#/evaluation/auto-revert) — sister gate with per-run focus. diff --git a/docs/usermanuals/en/getting-started/first-run.md b/docs/usermanuals/en/getting-started/first-run.md new file mode 100644 index 00000000..ff321591 --- /dev/null +++ b/docs/usermanuals/en/getting-started/first-run.md @@ -0,0 +1,146 @@ +--- +title: Your First Run +description: Run your first ForgeLM training job in 5 minutes — install, validate, train, evaluate. +--- + +# Your First Run + +This page walks you through a complete training run, from a fresh `pip install` to a finished checkpoint with audit artifacts. Allow ~5 minutes of reading and ~30 minutes of GPU time. + +```mermaid +flowchart LR + A[pip install] --> B[forgelm doctor] + B --> C[forgelm quickstart] + C --> D[--dry-run] + D --> E[--fit-check] + E --> F[Training] + F --> G[Eval + Annex IV] + G --> H[forgelm chat] + classDef setup fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef validate fill:#1c2030,stroke:#eab308,color:#e6e7ec + classDef run fill:#1c2030,stroke:#22c55e,color:#e6e7ec + class A,B,C setup + class D,E validate + class F,G,H run +``` + +## 1. Verify your environment + +Before anything else, run `forgelm doctor` to check that Python, PyTorch, CUDA, and any optional dependencies are wired up correctly: + +```shell +$ forgelm doctor +ForgeLM 0.5.2 +Python 3.11.4 · PyTorch 2.4.0 +CUDA available · driver 535.171 · NVIDIA RTX 4090 · 24 GB +bitsandbytes ✓ (installed) +Unsloth ✓ (installed) +``` + +:::tip +If `forgelm doctor` reports a problem (missing CUDA, version mismatch, no GPU), fix that first. Every other ForgeLM command will fail in confusing ways otherwise. See [Troubleshooting](#/operations/troubleshooting). +::: + +## 2. Pick a bundled template + +ForgeLM ships with five starter templates that cover most real-world fine-tuning scenarios. List them: + +```shell +$ forgelm quickstart --list + customer-support Multi-turn helpful + safe (SFT + DPO) + code-assistant Code-completion fine-tune (SFT + ORPO) + byod-domain-expert PDF/DOCX corpus → domain Q&A (SFT) + medical-qa-tr Turkish medical Q&A (SFT) + math-reasoning Step-by-step reasoning (GRPO) +``` + +For your first run, pick `customer-support` — it's small, finishes in ~30 minutes on a 12 GB GPU, and exercises every feature (SFT, DPO, eval, safety, audit): + +```shell +$ forgelm quickstart customer-support +Wrote configs/quickstart-customer-support.yaml +``` + +The generated YAML is yours to keep, edit, and version-control. Open it. + +## 3. Validate the config (`--dry-run`) + +Always validate before training. `--dry-run` parses your YAML, checks every referenced file exists, downloads metadata for the model and tokenizer, and reports any structural problems — without using a single GPU second: + +```shell +$ forgelm --config configs/quickstart-customer-support.yaml --dry-run +✓ config validates +✓ datasets reachable +✓ tokenizer downloadable +✓ output directory writable +``` + +:::warn +A failing `--dry-run` is a configuration problem, not a training problem. Fix it before going further. Most "training crashed at step 0" reports trace back to skipped dry-runs. +::: + +## 4. Estimate VRAM (`--fit-check`) + +Different models, different `max_length`, different LoRA ranks all change peak memory. `--fit-check` runs a static analysis and reports whether your job will fit: + +```shell +$ forgelm --config configs/quickstart-customer-support.yaml --fit-check +FITS est. peak 11.4 GB / 12 GB available +``` + +Possible verdicts: + +| Verdict | Meaning | +|---|---| +| `FITS` | Comfortably within VRAM budget. Proceed. | +| `TIGHT` | Within budget but no headroom for activation bursts. Reduce `max_length` or batch size. | +| `OOM` | Will not fit. Suggested fixes printed (e.g. enable QLoRA, lower batch size). | +| `UNKNOWN` | Architecture not in the GPU profile database — train conservatively or report. | + +## 5. Train + +```shell +$ forgelm --config configs/quickstart-customer-support.yaml +[2026-04-28 14:01:32] config validated +[2026-04-28 14:01:33] auditing data/customer-support.jsonl (12,400 rows, 3 splits) +[2026-04-28 14:01:35] PII flags: 0 critical, 5 medium · cross-split overlap: 0 +[2026-04-28 14:01:37] SFT epoch 1/3 · loss=2.31 → 1.42 +[2026-04-28 14:18:55] DPO preference pass · β=0.1 · KL=4.2 +[2026-04-28 14:32:11] benchmark hellaswag=0.62 truthfulqa=0.48 +[2026-04-28 14:33:02] Llama Guard S1-S14: clean +[2026-04-28 14:33:04] Annex IV → checkpoints/customer-support/artifacts/annex_iv.json +[2026-04-28 14:33:04] ✔ finished, exit 0 +``` + +## 6. Try the model + +```shell +$ forgelm chat ./checkpoints/customer-support +forgelm> how do I cancel my subscription? +You can cancel from Settings → Billing → Cancel subscription. Your access +continues until the end of the current billing period… +``` + +## What you got on disk + +```text +checkpoints/customer-support/ +├── artifacts/ +│ ├── annex_iv.json ← Article 11 technical documentation +│ ├── audit_log.jsonl ← Article 12 append-only event log +│ ├── data_audit_report.json ← Article 10 data governance evidence +│ ├── safety_report.json ← Llama Guard verdict +│ ├── benchmark_results.json ← Per-task accuracy +│ └── manifest.json ← SHA-256 over every artifact +├── README.md ← Article 13 model card +├── config_snapshot.yaml ← The exact YAML this run used +└── adapter_model.safetensors ← LoRA weights (or merged checkpoint) +``` + +That `artifacts/` directory is the deliverable for compliance reviews. Every file inside is hashed in `manifest.json` for tamper-evidence. + +## Next steps + +- [Project Layout](#/getting-started/project-layout) — where ForgeLM puts things and why. +- [Choosing a Trainer](#/concepts/choosing-trainer) — moving past `customer-support` to your own use case. +- [Configuration Reference](#/reference/configuration) — every YAML field, in detail. diff --git a/docs/usermanuals/en/getting-started/installation.md b/docs/usermanuals/en/getting-started/installation.md new file mode 100644 index 00000000..b049e067 --- /dev/null +++ b/docs/usermanuals/en/getting-started/installation.md @@ -0,0 +1,130 @@ +--- +title: Installation +description: Install ForgeLM from PyPI, with optional extras for ingestion, scale, and export. +--- + +# Installation + +ForgeLM ships as a single PyPI package with optional dependency groups (called *extras*) for the heavier features. Most users start with the base install and add extras as needed. + +## Requirements + +| Requirement | Minimum | Recommended | +|---|---|---| +| Python | 3.10 | 3.11+ | +| OS | Linux, macOS | Linux for GPU training | +| RAM | 8 GB | 16 GB+ | +| Disk | 5 GB free | 50 GB+ for model caches | +| GPU (training) | None for ingest/audit | Single 12 GB CUDA GPU minimum for SFT 7B | + +:::note +**No GPU?** You can still use ForgeLM for ingestion, audit, evaluation prep, and deployment config generation — every CPU-only workflow runs on the same `forgelm` command. +::: + +## Base install + +```shell +$ pip install forgelm +``` + +This gives you the trainer, all six alignment paradigms, evaluation, safety scoring, compliance artifact generation, and the CLI. It's enough to fine-tune a model end-to-end if your data is already in JSONL format. + +Verify the install: + +```shell +$ forgelm --version +$ forgelm --help +``` + +## Optional extras + +ForgeLM splits heavy or rarely-needed dependencies into extras so you don't pull them in unless you need them. + +### Document ingestion (`[ingestion]`) + +```shell +$ pip install 'forgelm[ingestion]' +``` + +Adds support for ingesting PDF, DOCX, EPUB, TXT, and Markdown files into SFT-ready JSONL via `forgelm ingest`. Pulls in `pypdf`, `python-docx`, `ebooklib`, and a few smaller text-handling libraries. + +### Large-corpus deduplication (`[ingestion-scale]`) + +```shell +$ pip install 'forgelm[ingestion-scale]' +``` + +Adds MinHash LSH (via `datasketch`) for near-duplicate detection on corpora bigger than ~50 K rows. The default simhash-based detector is fast and exact-recall, but MinHash scales to millions of rows. Pull this in only if you need the scale. + +### GGUF export (`[export]`) + +```shell +$ pip install 'forgelm[export]' +``` + +Adds quantized GGUF export for local inference (Ollama, llama.cpp). Pulls in the `gguf` writer and supporting libraries. Optional because not every workflow ends in GGUF — many users hand off to vLLM or TGI directly. + +### Distributed training (`[deepspeed]`) + +```shell +$ pip install 'forgelm[deepspeed]' +``` + +Adds DeepSpeed ZeRO-2 / ZeRO-3 support for multi-GPU training. Required only if you're training a model larger than fits on a single GPU. + +### Everything (`[all]`) + +```shell +$ pip install 'forgelm[all]' +``` + +Pulls in every extra. Useful for CI runners that need to test all code paths; not recommended for production environments where you want a minimal dependency tree. + +## Container install + +If you'd rather not install Python dependencies on your host, the official Docker image bundles ForgeLM with all extras: + +```shell +$ docker pull ghcr.io/cemililik/forgelm:latest +$ docker run --gpus all -v $PWD:/workspace ghcr.io/cemililik/forgelm:latest \ + forgelm --config /workspace/configs/run.yaml +``` + +A `docker-compose.yml` is also published; see [Docker Operations](#/operations/docker) for the multi-service pattern (training + experiment tracking + webhook receiver). + +## Verifying GPU access + +If you've installed ForgeLM for GPU training, confirm CUDA is wired up correctly: + +```shell +$ forgelm doctor +``` + +`forgelm doctor` reports: +- Python and PyTorch versions +- CUDA availability and driver version +- Detected GPU model and VRAM +- Available compute capability +- bitsandbytes / Unsloth detection (if installed) + +:::tip +Run `forgelm doctor` *before* `forgelm --config ...` for any new environment. It catches missing CUDA libraries, version mismatches, and GPU-not-found errors in two seconds rather than two hours into training. +::: + +## Common installation issues + +:::warn +**`bitsandbytes` import error on macOS / Apple Silicon.** `bitsandbytes` does not currently support Metal/MPS. On macOS, ForgeLM falls back to full-precision training. For 4-bit quantized training (QLoRA), you need a Linux host with a CUDA GPU. +::: + +:::warn +**`undefined symbol: __cudaRegisterFatBinaryEnd`.** Your PyTorch and CUDA toolkit versions are mismatched. Reinstall PyTorch matching your CUDA version: `pip install torch --index-url https://download.pytorch.org/whl/cu121` (replace `cu121` with your CUDA version). +::: + +:::warn +**`OSError: HuggingFace token not found`.** Some models (e.g. Llama 3, Llama Guard) require a HuggingFace access token. Set it via `huggingface-cli login` or the `HF_TOKEN` environment variable. See [CLI Reference](#/reference/cli) for all auth env vars. +::: + +## Next steps + +Now that ForgeLM is installed, head to [Your First Run](#/getting-started/first-run) for an end-to-end training walkthrough — you'll have a fine-tuned model in about 5 minutes of reading and 30 minutes of GPU time. diff --git a/docs/usermanuals/en/getting-started/introduction.md b/docs/usermanuals/en/getting-started/introduction.md new file mode 100644 index 00000000..5b4c1cc8 --- /dev/null +++ b/docs/usermanuals/en/getting-started/introduction.md @@ -0,0 +1,107 @@ +--- +title: Introduction +description: What ForgeLM is, who it's for, and what you can do with it. +--- + +# Welcome to ForgeLM + +**ForgeLM is a YAML-driven, enterprise-ready LLM fine-tuning toolkit.** You feed it a configuration file; it returns a fine-tuned model along with the audit trail, safety report, and Annex IV technical documentation a regulator would expect to see. + +This user guide covers every feature in detail — concepts, configuration parameters, common pitfalls, and copy-pasteable YAML you can adapt to your own workflows. + +## Who this guide is for + +ForgeLM is built for three audiences in particular: + +- **ML engineers** who need to ship fine-tuned models into regulated production environments and want a reproducible, scriptable workflow. +- **Compliance teams** who need to demonstrate to auditors that the model's training data, evaluation, and deployment follow EU AI Act, GDPR, or sector-specific requirements. +- **Platform/MLOps engineers** who run training as part of CI/CD pipelines and need predictable exit codes, structured logs, and webhook integrations. + +If you're brand new to LLM fine-tuning, the [Concepts](#/concepts/alignment-overview) section explains the underlying ideas before we get into configuration. + +## How a ForgeLM run actually flows + +```mermaid +flowchart LR + A[Raw documents
or JSONL] --> B[forgelm ingest] + B --> C[forgelm audit] + C -->|PII / leakage
flagged| C + C --> D[--dry-run
--fit-check] + D --> E[forgelm
training] + E --> F[Benchmark
+ safety eval] + F -->|regression| G[Auto-revert] + G --> E + F -->|pass| H[Annex IV
artifacts] + H --> I[Export &
deploy] + classDef start fill:#1c2030,stroke:#f97316,color:#e6e7ec + classDef ok fill:#161a24,stroke:#22c55e,color:#e6e7ec + classDef warn fill:#161a24,stroke:#eab308,color:#e6e7ec + classDef end1 fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + class A start + class B,C,D ok + class E,F warn + class G,H,I end1 +``` + +Every node maps to a `forgelm` command — there's no orchestrator that lives outside the toolkit. CI/CD systems just chain these commands together with the exit codes as gates. + +## What you can do with ForgeLM + +:::tip +Every capability listed below is opt-in via YAML. You only pay the complexity cost for the features you actually enable. +::: + +| Stage | What ForgeLM gives you | +|---|---| +| **Data preparation** | PDF / DOCX / EPUB / TXT / Markdown ingestion, PII masking, secrets scrubbing, near-duplicate detection, quality filtering, language detection, cross-split leakage checks | +| **Training** | Six post-training paradigms (SFT, DPO, SimPO, KTO, ORPO, GRPO), QLoRA / DoRA / GaLore, DeepSpeed ZeRO-2/3, FSDP, Unsloth backend | +| **Evaluation** | `lm-evaluation-harness` integration, LLM-as-judge with OpenAI or local models, Llama Guard safety scoring with auto-revert | +| **Compliance** | EU AI Act Annex IV artifact generation, append-only audit log with SHA-256 manifests, conformity declaration scaffolding | +| **Deployment** | GGUF export with 6 quantization levels, deploy configs for Ollama / vLLM / TGI / HuggingFace Endpoints, model card auto-generation | + +## How this guide is organised + +The sidebar groups topics by lifecycle stage: + +1. **Getting Started** — install ForgeLM, run your first training job, understand the project layout. +2. **Core Concepts** — the alignment stack, choosing a trainer, dataset formats. +3. **Training & Alignment** — every trainer (SFT, DPO, SimPO, KTO, ORPO, GRPO) and every parameter-efficient technique (LoRA, QLoRA, DoRA, GaLore). +4. **Data** — ingestion, audit, masking, deduplication. +5. **Evaluation & Safety** — benchmarks, judges, Llama Guard, auto-revert. +6. **Compliance** — Annex IV, audit logs, GDPR. +7. **Operations** — CI/CD, webhooks, distributed training, air-gap, troubleshooting. +8. **Deployment** — chat, GGUF, deploy targets, model merging. +9. **Reference** — full configuration schema, CLI reference, exit codes. + +## Where to start + +:::note +**New to ForgeLM?** Read [Installation](#/getting-started/installation) and [Your First Run](#/getting-started/first-run) in order — about 10 minutes of reading. +::: + +:::note +**Trying to fine-tune a specific model?** Skip to [Choosing a Trainer](#/concepts/choosing-trainer) — the decision tree there points you at the right configuration. +::: + +:::note +**Auditing a deployment for compliance?** Jump to [Compliance Overview](#/compliance/overview) and the [Configuration Reference](#/reference/configuration). +::: + +## Conventions used in this guide + +- **YAML snippets** show configuration as you'd put it in your config file. Top-level keys are always shown so you can copy them in context. +- **Shell commands** start with `$` to indicate the prompt — don't include the `$` when you copy. +- **`code`** in inline text refers to a CLI flag, configuration key, or file path. +- **Callout boxes** flag information that doesn't fit the main flow: + - Note — additional context. + - Tip — recommended practice. + - Warning — common pitfall. + - Danger — operational risk; read before proceeding. + +:::warn +ForgeLM operates on real models and real data on real GPUs. A misconfigured run can produce a model that fails safety thresholds, leaks PII, or simply costs you a lot in wasted GPU time. The dry-run and fit-check workflows ([Your First Run](#/getting-started/first-run)) exist to catch these problems before they cost you anything — use them. +::: + +## A note on technical terms + +ForgeLM's documentation keeps technical terms in their original form across all languages — `SFT`, `DPO`, `LoRA`, `QLoRA`, `Annex IV`, `GGUF`, `vLLM`, etc. This is intentional: these are the terms you'll find in research papers, library APIs, and config files, and translating them creates ambiguity. General prose around them is fully translated. diff --git a/docs/usermanuals/en/getting-started/project-layout.md b/docs/usermanuals/en/getting-started/project-layout.md new file mode 100644 index 00000000..56eee374 --- /dev/null +++ b/docs/usermanuals/en/getting-started/project-layout.md @@ -0,0 +1,125 @@ +--- +title: Project Layout +description: How ForgeLM organises configs, data, checkpoints, and artifacts on disk. +--- + +# Project Layout + +ForgeLM is opinionated about *where* files go. This makes runs reproducible, CI/CD pipelines predictable, and audit reviewers happy. You don't have to follow this layout exactly — but every override has a flag, and the defaults assume the conventions below. + +## A typical project tree + +```text +my-finetune/ +├── configs/ — YAML configuration files +│ ├── customer-support.yaml — your trainer config +│ └── customer-support.dev.yaml — fast variant for iteration +├── data/ — JSONL datasets +│ ├── train.jsonl +│ ├── validation.jsonl +│ └── preferences.jsonl — DPO/SimPO chosen-rejected pairs +├── audit/ — output of `forgelm audit` +│ └── data_audit_report.json +├── checkpoints/ — model outputs (gitignored) +│ └── customer-support/ +│ ├── adapter_model.safetensors +│ ├── README.md — model card (Article 13) +│ ├── config_snapshot.yaml — frozen copy of the config used +│ └── artifacts/ — compliance evidence bundle +├── ingested/ — raw documents → JSONL via `forgelm ingest` +└── .forgelm/ — local cache (also gitignored) +``` + +## Where each command writes + +| Command | Writes to | Notes | +|---|---|---| +| `forgelm ingest` | `--output` (typically `data/*.jsonl`) | Raw docs → SFT-ready JSONL. | +| `forgelm audit` | `--output` (typically `audit/`) | PII / leakage / quality report. | +| `forgelm --config X.yaml` | `output.dir` from YAML | Full training artifacts. | +| `forgelm export` | `--output` (path to `.gguf`) | Quantised single-file model. | +| `forgelm deploy` | `--output` (Modelfile, K8s manifest, etc.) | Deployment scaffolds. | +| `forgelm chat` | nothing (interactive) | Streams to terminal. | + +## What to commit, what to gitignore + +:::tip +ForgeLM's defaults play well with version control if you commit the right things and ignore the rest. +::: + +**Commit:** +- `configs/*.yaml` — your runs are configurations; the YAML is the source of truth. +- `audit/*.json` — small, machine-readable, useful in PR reviews ("did the audit numbers regress?"). +- `checkpoints/*/README.md` and `checkpoints/*/artifacts/` (model card and audit bundle, both small). + +**Gitignore:** +- `data/` — usually too large; track via DVC or your preferred dataset registry instead. +- `checkpoints/*/adapter_model.safetensors` and other weight files — too large for git, push to HuggingFace Hub or model registry. +- `ingested/` — re-buildable from raw documents. +- `.forgelm/` — local cache. + +A starter `.gitignore`: + +```gitignore +# ForgeLM defaults +checkpoints/*/adapter_model.safetensors +checkpoints/*/*.safetensors +checkpoints/*/pytorch_model.bin +checkpoints/*/optimizer.pt +data/ +ingested/ +.forgelm/ +``` + +## Repository conventions + +ForgeLM uses these path conventions — change them with command-line flags but keep them consistent across a project: + +| Convention | Default | Override | +|---|---|---| +| Config file | `configs/.yaml` | `--config PATH` | +| Audit output | `./audit/` | `forgelm audit --output PATH` | +| Training output | `./checkpoints//` | `output.dir:` in YAML | +| Cache directory | `~/.forgelm/cache/` | `FORGELM_CACHE_DIR` env var | +| HuggingFace token | env `HF_TOKEN` | `auth.hf_token:` in YAML | + +## Multi-config workflows + +Most teams keep two YAMLs per project — a fast "dev" config (1 epoch, small subset, no safety eval) for rapid iteration and a "prod" config that enables every gate: + +```text +configs/ +├── customer-support.yaml — full run (use this for releases) +└── customer-support.dev.yaml — dev iteration (faster) +``` + +The dev YAML can `extends:` the prod one to avoid duplication: + +```yaml +# customer-support.dev.yaml +extends: "customer-support.yaml" +training: + epochs: 1 # was 3 + max_steps: 200 # cap iterations +data: + - path: "data/dev/100rows.jsonl" +evaluation: + benchmark: { enabled: false } + safety: { enabled: false } +``` + +Run the dev variant during development, the full one for release. CI runs the full one on every merge to main. + +## Where compliance artifacts go + +Every successful (or failed) training run creates a `checkpoints//artifacts/` directory containing the evidence bundle described in [Compliance Overview](#/compliance/overview). This is the directory you hand to a regulator or pin in your CI artifacts. + +:::warn +**Don't merge the artifacts/ directory across runs.** Each run is a separate evidence bundle; mixing them breaks the SHA-256 manifest and undermines tamper-evidence. +::: + +## See also + +- [Configuration Reference](#/reference/configuration) — every field that controls these paths. +- [CI/CD Pipelines](#/operations/cicd) — how to wire this layout into GitHub Actions. +- [Audit Log](#/compliance/audit-log) — how the artifacts directory is used. diff --git a/docs/usermanuals/en/operations/air-gap.md b/docs/usermanuals/en/operations/air-gap.md new file mode 100644 index 00000000..326f3c30 --- /dev/null +++ b/docs/usermanuals/en/operations/air-gap.md @@ -0,0 +1,159 @@ +--- +title: Air-Gap Operation +description: Train and evaluate without internet — pre-cache everything, run in isolated networks. +--- + +# Air-Gap Operation + +For regulated industries (defence, healthcare, certain financial sectors) and high-security customer environments, training must happen on networks with no internet access. ForgeLM is designed to operate fully air-gapped: every internet-touching step has an offline equivalent. + +## What needs to be online (one-time) + +Before going air-gapped, pre-cache: + +| Resource | Where to cache | +|---|---| +| Base model | `~/.cache/huggingface/hub/` | +| Tokeniser | (same — bundled with model) | +| Llama Guard | `~/.cache/huggingface/hub/` | +| `lm-evaluation-harness` task definitions | `~/.cache/lm-evaluation-harness/` | +| Python packages (`forgelm` + extras) | local pip wheel cache | + +Pre-cache from a connected machine: + +```shell +$ forgelm cache-models \ + --model "Qwen/Qwen2.5-7B-Instruct" \ + --safety "meta-llama/Llama-Guard-3-8B" \ + --output ./airgap-bundle/ + +$ forgelm cache-tasks \ + --tasks hellaswag,arc_easy,truthfulqa,mmlu \ + --output ./airgap-bundle/ +``` + +Transfer `airgap-bundle/` to the offline host (USB, scp, whatever your security policy allows). + +## On the air-gapped host + +Set environment variables to point at the local cache and disable any network calls: + +```shell +$ export HF_HOME="$(pwd)/airgap-bundle/huggingface" +$ export TRANSFORMERS_OFFLINE=1 +$ export HF_HUB_OFFLINE=1 +$ export HF_DATASETS_OFFLINE=1 + +$ forgelm --config configs/run.yaml --offline +``` + +The `--offline` flag tells ForgeLM to refuse any network call. If your config references a model that isn't cached, training fails with a clear error message: + +```text +ERROR: model "meta-llama/Llama-Guard-3-8B" not in local cache. + Pre-cache from a connected machine: forgelm cache-models --safety meta-llama/Llama-Guard-3-8B +``` + +## What `--offline` enforces + +| Subsystem | Behaviour with `--offline` | +|---|---| +| HuggingFace Hub downloads | Disabled. Fail-fast if a model/tokeniser isn't cached. | +| W&B / MLflow / Comet | Disabled (or local-only for MLflow with file URI). | +| OpenAI / Anthropic judges | Disabled. Use a local judge model. | +| Webhooks | Disabled (or restricted to internal hosts via `webhook.allow_private`). | +| pip install (during runtime) | Disabled. | +| Telemetry | None — ForgeLM never phones home regardless. | + +## Local synthetic data + +If you need synthetic data generation in air-gap, use a local teacher: + +```yaml +synthetic: + enabled: true + teacher: + provider: "local" + model: "Qwen/Qwen2.5-72B-Instruct" # must be cached + load_in_4bit: true +``` + +OpenAI / Anthropic providers fail on `--offline`. + +## Local LLM-as-judge + +```yaml +evaluation: + judge: + enabled: true + judge_model: + provider: "local" + model: "Qwen/Qwen2.5-72B-Instruct" +``` + +A 72B local judge is slower than `gpt-4o-mini` but the quality is comparable for typical use cases. See [LLM-as-Judge](#/evaluation/judge). + +## Evaluation in air-gap + +`lm-evaluation-harness` typically downloads task definitions and datasets at runtime. Pre-cache them: + +```shell +$ forgelm cache-tasks --tasks hellaswag,arc_easy,truthfulqa,mmlu +``` + +Configure ForgeLM to use the cache: + +```yaml +evaluation: + benchmark: + tasks_dir: "${HF_HOME}/lm-evaluation-harness/" +``` + +## Verifying air-gap mode + +```shell +$ forgelm doctor --offline +ForgeLM 0.5.2 (offline mode verified) +✓ HF_HUB_OFFLINE set +✓ TRANSFORMERS_OFFLINE set +✓ Local cache: airgap-bundle/huggingface (3.4 GB cached models) +✓ Llama Guard 3 8B available locally +✓ lm-evaluation-harness: 4 tasks cached +``` + +If `forgelm doctor --offline` reports anything unavailable, fix that *before* the air-gapped operator wastes their time. + +## Bundle size estimate + +For a typical fine-tuning project: + +| Resource | Approx size | +|---|---| +| Base model (7B) in safetensors | 14 GB | +| Llama Guard 3 8B | 16 GB | +| Tokeniser + config | <100 MB | +| Eval task definitions + cached datasets | 500 MB - 2 GB | +| Python wheels (forgelm + extras) | 1-2 GB | +| **Total** | **~32-34 GB** | + +Plan storage accordingly. + +## Common pitfalls + +:::warn +**Forgetting to set the environment variables.** Without `HF_HUB_OFFLINE=1`, HuggingFace libraries silently try to phone home and fall back to local cache. The fall-back works fine but you've now made an outbound connection — a compliance violation in some environments. +::: + +:::warn +**Using `--offline` without pre-caching.** Training will fail at the first model load. Run `forgelm doctor --offline` before kicking off training to catch missing resources upfront. +::: + +:::tip +**Build a CI image with everything pre-cached.** For air-gapped CI, package the pre-cached bundle into a Docker image. Every CI run starts from the cached state. See [Docker](#/operations/docker). +::: + +## See also + +- [Docker](#/operations/docker) — building images with pre-cached models. +- [Installation](#/getting-started/installation) — base install. +- [LLM-as-Judge](#/evaluation/judge) — local judge models. diff --git a/docs/usermanuals/en/operations/cicd.md b/docs/usermanuals/en/operations/cicd.md new file mode 100644 index 00000000..20b06750 --- /dev/null +++ b/docs/usermanuals/en/operations/cicd.md @@ -0,0 +1,197 @@ +--- +title: CI/CD Pipelines +description: Wire ForgeLM into GitHub Actions, GitLab CI, or Jenkins with predictable exit codes. +--- + +# CI/CD Pipelines + +ForgeLM is designed to run as a CI/CD pipeline step, not as an interactive notebook. Every command has a predictable exit code, every output is structured (JSON or JSONL), and every gate either passes or fails — no in-between. + +## The exit-code contract + +| Exit | Meaning | What CI should do | +|---|---|---| +| `0` | Success | Promote artifacts | +| `1` | Configuration error | Fail; fix YAML before retry | +| `2` | Audit warnings | Block merge until reviewed | +| `3` | Auto-revert triggered | Fail; investigate regression | +| `4` | Awaiting human approval | Hold pipeline; trigger reviewer notification | + +See [Exit Codes](#/reference/exit-codes) for the full contract. + +## GitHub Actions + +A complete pipeline: + +```yaml +# .github/workflows/train.yml +name: Train and evaluate + +on: + push: + branches: [main] + paths: + - "configs/**" + - "data/**.jsonl" + workflow_dispatch: + +jobs: + audit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 + with: { python-version: "3.11" } + - run: pip install 'forgelm[ingestion]' + - name: Audit data + run: forgelm audit data/train.jsonl --strict + + train: + needs: audit + runs-on: gpu-runner # self-hosted with CUDA + steps: + - uses: actions/checkout@v5 + - run: pip install forgelm + - name: Validate config + run: forgelm --config configs/run.yaml --dry-run + - name: Fit-check VRAM + run: forgelm --config configs/run.yaml --fit-check + - name: Train + run: forgelm --config configs/run.yaml + - name: Upload artifacts + if: always() + uses: actions/upload-artifact@v4 + with: + name: training-artifacts + path: checkpoints/run/artifacts/ +``` + +Note the `if: always()` on artifact upload — even on failure, the audit log and partial artifacts are useful. + +## GitLab CI + +```yaml +# .gitlab-ci.yml +stages: + - audit + - train + - deploy + +audit: + stage: audit + image: python:3.11 + script: + - pip install 'forgelm[ingestion]' + - forgelm audit data/train.jsonl --strict + +train: + stage: train + tags: [gpu] + script: + - pip install forgelm + - forgelm --config configs/run.yaml --dry-run + - forgelm --config configs/run.yaml --fit-check + - forgelm --config configs/run.yaml + artifacts: + paths: + - checkpoints/run/artifacts/ + when: always +``` + +## Jenkins + +```groovy +pipeline { + agent any + stages { + stage('Audit') { + steps { + sh 'forgelm audit data/train.jsonl --strict' + } + } + stage('Train') { + agent { label 'gpu' } + steps { + sh 'forgelm --config configs/run.yaml --dry-run' + sh 'forgelm --config configs/run.yaml --fit-check' + sh 'forgelm --config configs/run.yaml' + } + post { + always { + archiveArtifacts artifacts: 'checkpoints/run/artifacts/**' + } + } + } + } +} +``` + +## JSON output mode + +For programmatic parsing of run outputs, use `--output-format json`: + +```shell +$ forgelm --config configs/run.yaml --output-format json | jq '.verdict' +"success" +``` + +Every event ForgeLM logs to stderr is also emitted as a JSON object on stdout, ready to pipe into your log aggregator or dashboard. + +## Caching models + +Model downloads are the slowest part of a fresh CI run. Cache them: + +```yaml +# GitHub Actions +- uses: actions/cache@v4 + with: + path: ~/.cache/huggingface + key: hf-${{ runner.os }}-${{ hashFiles('configs/**.yaml') }} +``` + +For multi-runner setups, point the cache at shared storage (S3, NFS) so all runners share it. + +## Concurrency control + +Most projects run training serially, not in parallel — multiple concurrent jobs on the same GPU lead to OOM. Use concurrency: + +```yaml +# GitHub Actions +concurrency: + group: training-${{ github.ref }} + cancel-in-progress: false # don't cancel; queue +``` + +## Self-hosted GPU runners + +For GitHub Actions with self-hosted GPUs: + +1. Install the GitHub runner on the GPU host. +2. Tag it: `self-hosted, linux, x64, gpu`. +3. Reference in your job: `runs-on: [self-hosted, gpu]`. + +ForgeLM ships a `Dockerfile.runner` reference for setting up the runner with CUDA, Python, and pre-installed extras. + +## Common pitfalls + +:::warn +**Suppressing exit codes.** `forgelm ... || true` defeats the entire purpose of the gate contract. If you genuinely need to keep going, branch on the exit code instead. +::: + +:::warn +**Running audit and train on the same runner.** Audit is CPU-only; training needs a GPU. Run audit on a cheap runner first, then train on the GPU runner only if audit passes. Saves GPU time when data has bugs. +::: + +:::warn +**No artifact upload on failure.** When a run fails, the audit log is the most valuable evidence. Always set `if: always()` (GitHub) / `when: always` (GitLab) on artifact uploads. +::: + +:::tip +For overnight training runs, configure auto-revert + Slack webhook. You'll either wake up to a promoted model or a clear incident report — never a "dunno, broke at 3am" mystery. +::: + +## See also + +- [Exit Codes](#/reference/exit-codes) — the contract CI relies on. +- [Webhooks](#/operations/webhooks) — Slack/Teams notifications. +- [Auto-Revert](#/evaluation/auto-revert) — what triggers exit 3. diff --git a/docs/usermanuals/en/operations/docker.md b/docs/usermanuals/en/operations/docker.md new file mode 100644 index 00000000..f4dbe6de --- /dev/null +++ b/docs/usermanuals/en/operations/docker.md @@ -0,0 +1,149 @@ +--- +title: Docker +description: Reproducible runs across local, on-prem, and cloud — same image, same behaviour. +--- + +# Docker + +ForgeLM ships an official Dockerfile and `docker-compose.yml` for reproducible training runs across local development, on-prem clusters, and cloud GPUs. + +## Quick start + +Pull the official image: + +```shell +$ docker pull ghcr.io/cemililik/forgelm:latest +$ docker run --gpus all \ + -v $PWD:/workspace \ + -v $HOME/.cache/huggingface:/root/.cache/huggingface \ + -e HF_TOKEN \ + ghcr.io/cemililik/forgelm:latest \ + forgelm --config /workspace/configs/run.yaml +``` + +The `--gpus all` flag requires NVIDIA Container Toolkit on the host. Mount your project as `/workspace` and the HuggingFace cache so model downloads persist across runs. + +## Image variants + +| Tag | Includes | Size | +|---|---|---| +| `latest` | Base + all extras (ingestion, scale, export, deepspeed) | ~12 GB | +| `slim` | Base only — no extras | ~6 GB | +| `airgap` | Base + extras + pre-cached Qwen 2.5 7B + Llama Guard | ~30 GB | + +For most teams, `latest` is the right pick. For air-gap deployments, build a custom image based on `airgap` with your specific models pre-cached. See [Air-Gap Operation](#/operations/air-gap). + +## docker-compose + +For multi-service local development (training + experiment tracking + webhook receiver): + +```yaml +# docker-compose.yml +version: "3.9" + +services: + trainer: + image: ghcr.io/cemililik/forgelm:latest + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] + volumes: + - .:/workspace + - hf-cache:/root/.cache/huggingface + environment: + - HF_TOKEN + - WANDB_API_KEY + - SLACK_WEBHOOK + command: forgelm --config /workspace/configs/run.yaml + + mlflow: + image: ghcr.io/mlflow/mlflow:latest + ports: + - "5000:5000" + volumes: + - ./mlruns:/mlflow/mlruns + command: mlflow server --host 0.0.0.0 --port 5000 + +volumes: + hf-cache: {} +``` + +```shell +$ docker compose up trainer +``` + +## Building from source + +If you need custom modifications: + +```shell +$ git clone https://github.com/cemililik/ForgeLM +$ cd ForgeLM +$ docker build -t forgelm:custom -f Dockerfile . +$ docker run --gpus all forgelm:custom forgelm --version +``` + +The `Dockerfile` is multi-stage: a builder stage installs heavy dependencies (CUDA, PyTorch, bitsandbytes), then a runtime stage copies in the compiled artefacts. Total build time: ~15 minutes on a fast connection. + +## Air-gap image + +For air-gapped environments, build an image with everything pre-cached: + +```dockerfile +# airgap.Dockerfile +FROM ghcr.io/cemililik/forgelm:latest + +# Pre-cache the base model +RUN forgelm cache-models --model "Qwen/Qwen2.5-7B-Instruct" + +# Pre-cache Llama Guard +RUN forgelm cache-models --safety "meta-llama/Llama-Guard-3-8B" + +# Pre-cache eval tasks +RUN forgelm cache-tasks --tasks hellaswag,arc_easy,truthfulqa,mmlu + +# Force offline mode in container +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 +ENV HF_DATASETS_OFFLINE=1 + +ENTRYPOINT ["forgelm"] +CMD ["--help"] +``` + +Build, save, transfer: + +```shell +$ docker build -t forgelm-airgap -f airgap.Dockerfile . +$ docker save forgelm-airgap | gzip > forgelm-airgap.tar.gz +# Transfer forgelm-airgap.tar.gz to the air-gapped host +$ docker load < forgelm-airgap.tar.gz +``` + +## Common pitfalls + +:::warn +**Forgetting `--gpus all`.** Without it, the container can't see your GPU and ForgeLM falls back to CPU — training a 7B model on CPU is impossible. +::: + +:::warn +**Not mounting the HuggingFace cache.** Every container start re-downloads the base model (15+ GB). Always mount `~/.cache/huggingface` so downloads persist. +::: + +:::warn +**Hardcoded API keys in Dockerfile.** Build args bake values into the image layer history. Use runtime environment variables instead: `docker run -e HF_TOKEN ...`. +::: + +:::tip +For Kubernetes deployments, use the same image with a custom resource definition pointing at GPU nodes. ForgeLM's behaviour is identical — just the orchestration layer changes. +::: + +## See also + +- [Air-Gap Operation](#/operations/air-gap) — for fully offline deployments. +- [CI/CD Pipelines](#/operations/cicd) — using the image in GitHub Actions. +- [Installation](#/getting-started/installation) — non-Docker install. diff --git a/docs/usermanuals/en/operations/experiment-tracking.md b/docs/usermanuals/en/operations/experiment-tracking.md new file mode 100644 index 00000000..6a678af3 --- /dev/null +++ b/docs/usermanuals/en/operations/experiment-tracking.md @@ -0,0 +1,143 @@ +--- +title: Experiment Tracking +description: W&B, MLflow, and TensorBoard integration via the report_to setting. +--- + +# Experiment Tracking + +ForgeLM doesn't reinvent experiment tracking — it integrates with whatever your team already uses via the `training.report_to` field. W&B, MLflow, TensorBoard, and Comet ML are first-class. + +## Quick example + +```yaml +training: + trainer: "sft" + report_to: ["wandb", "tensorboard"] # both at once + run_name: "customer-support-v1.2.0" + tags: ["dpo", "qlora", "tr"] +``` + +ForgeLM streams loss, learning rate, evaluation metrics, and benchmark scores to every configured backend. + +## Supported backends + +### Weights & Biases (W&B) + +```yaml +training: + report_to: ["wandb"] + wandb: + project: "forgelm-customer-support" + entity: "acme-ml" + api_key: "${WANDB_API_KEY}" + log_artifacts: true # upload checkpoints to W&B +``` + +Auth: set `WANDB_API_KEY` environment variable, or run `wandb login` once on the training host. + +### MLflow + +```yaml +training: + report_to: ["mlflow"] + mlflow: + tracking_uri: "http://mlflow.internal:5000" + experiment_name: "customer-support" + registry_uri: "http://mlflow.internal:5000" + log_model: true # promote to MLflow Model Registry +``` + +Auth: standard MLflow env vars (`MLFLOW_TRACKING_USERNAME`, `MLFLOW_TRACKING_PASSWORD`, or token). + +### TensorBoard + +```yaml +training: + report_to: ["tensorboard"] + tensorboard: + log_dir: "${output.dir}/tensorboard" +``` + +No external service needed — log files are local. + +### Comet ML + +```yaml +training: + report_to: ["comet_ml"] + comet_ml: + api_key: "${COMET_API_KEY}" + project_name: "forgelm-customer-support" +``` + +## What gets logged + +| Metric | When | +|---|---| +| `train/loss` | Every step | +| `train/lr` | Every step | +| `train/grad_norm` | Every step (if `log_grad_norm: true`) | +| `eval/loss` | Every eval interval | +| `benchmark/` | Once per run (after eval) | +| `safety//max` | Once per run (after safety eval) | +| `safety//mean` | Once per run | +| `system/gpu_utilization` | Sampled every 30s | +| `system/vram_used_gb` | Sampled every 30s | + +## Run naming and tags + +```yaml +training: + run_name: "customer-support-{config_hash}" # interpolation supported + tags: ["dpo", "qlora", "tr", "v1.2"] + notes: "Increased beta from 0.1 to 0.15 to chase truthfulqa floor" +``` + +The `notes` field is recorded in every backend that supports prose annotations. + +## Artifact management + +For W&B and MLflow, ForgeLM can upload the checkpoint and audit bundle as artifacts: + +```yaml +training: + wandb: + log_artifacts: true # full checkpoint + bundle + artifact_type: "model" +``` + +For very large checkpoints, prefer model registries (HuggingFace Hub) over W&B/MLflow artifact stores. Their free tiers cap at smallish sizes. + +## Comparing runs + +Each backend's UI handles comparison naturally — comparable runs share a `run_name` prefix, tags, and config hash. ForgeLM's CLI also helps: + +```shell +$ forgelm compare-runs runs/v1.0 runs/v1.1 runs/v1.2 + v1.0 v1.1 v1.2 +hellaswag 0.612 0.617 0.621 +truthfulqa 0.480 0.482 0.475 ↓ +S5_max 0.041 0.038 0.082 ↑↑ +loss 1.43 1.39 1.35 +``` + +The arrows are auto-derived: green for improvement, red for regression of significance. + +## Common pitfalls + +:::warn +**Hardcoding API keys.** Never put W&B / MLflow / Comet keys directly in YAML. Always use `${ENV_VAR}` interpolation. Check `audit_log.jsonl` to confirm secrets weren't included in the dumped config. +::: + +:::warn +**Reporting to unreachable backends.** If `wandb.ai` is down or your firewall blocks it, ForgeLM logs a warning but doesn't fail training. Watch the warnings; otherwise you might miss that nothing's being logged. +::: + +:::tip +**Use multiple backends in parallel.** TensorBoard for local debugging during a run, W&B for cross-team collaboration after. Configure both — there's no extra cost. +::: + +## See also + +- [Configuration Reference](#/reference/configuration) — full `report_to` and per-backend settings. +- [JSON Output Mode](#/operations/cicd) — for piping logs into your own tracking. diff --git a/docs/usermanuals/en/operations/gpu-cost.md b/docs/usermanuals/en/operations/gpu-cost.md new file mode 100644 index 00000000..e8440df4 --- /dev/null +++ b/docs/usermanuals/en/operations/gpu-cost.md @@ -0,0 +1,143 @@ +--- +title: GPU Cost Estimation +description: Auto-detect across 18 GPU profiles and track per-run cost against your hourly rate. +--- + +# GPU Cost Estimation + +ForgeLM detects the GPU you're running on, looks up its profile (memory, compute, typical hourly rate), and tracks per-run cost. After every run, the audit log records exactly how much GPU time was used and what it cost. + +## How detection works + +On startup, `forgelm` reads: +- `nvidia-smi --query-gpu=name,memory.total,...` for hardware identification. +- The matching profile from `forgelm/gpu_profiles.yaml`. + +Supported GPUs include: + +| Class | Models | +|---|---| +| Datacenter | A100 40 GB / 80 GB, H100 80 GB, H200, L40S | +| Workstation | RTX 6000 Ada, RTX A6000 | +| Consumer | RTX 4090, RTX 4080, RTX 3090, RTX 3080 | +| Cloud-only | T4, V100, A10G | +| Apple | M1/M2/M3 Max (CPU/MPS fallback) | + +If your GPU isn't recognised, ForgeLM logs a warning and falls back to a generic profile (no cost estimation, but training works). + +## Configuring your hourly rate + +```yaml +output: + cost_tracking: + enabled: true + rate_per_hour: + A100_80GB: 1.10 # USD per hour + A100_40GB: 0.85 + H100_80GB: 2.40 + RTX_4090: 0.50 # rough cost-of-electricity + default: 1.00 # for unmatched GPUs + currency: "USD" +``` + +Set this once per project. ForgeLM uses the matched rate for cost reporting. + +## Output + +After each run, the audit log records: + +```json +{ + "event": "run_complete", + "ts": "2026-04-29T14:33:10Z", + "duration_seconds": 1892, + "gpu_profile": "A100_80GB", + "gpus_used": 1, + "estimated_cost_usd": 0.578, + "rate_per_hour": 1.10, + "currency": "USD" +} +``` + +The model card cites it: + +```markdown +## Training cost + +This model was trained for 31m 32s on 1× A100 80GB, +estimated at $0.58 USD at the configured rate. +``` + +## Pre-flight cost estimation + +Before starting a long training run, get an estimate: + +```shell +$ forgelm --config configs/run.yaml --estimate-cost +Estimated training time: 6h 30m +Estimated cost (1× A100 80GB at $1.10/hr): $7.15 +``` + +The estimate uses dataset size + epochs + per-step throughput from a small calibration run. Accuracy is typically within 20% of actual. + +## Multi-GPU and distributed + +For multi-GPU training, ForgeLM multiplies the per-GPU rate by the GPU count: + +```yaml +output: + cost_tracking: + rate_per_hour: + A100_80GB: 1.10 +``` + +A 4×A100 run for 2 hours = 4 × 2 × $1.10 = $8.80, regardless of whether you use ZeRO or FSDP. + +## Cost alerts + +For runs that may run away: + +```yaml +output: + cost_tracking: + alert_threshold_usd: 50.0 # webhook fires when crossed + halt_threshold_usd: 200.0 # training stops +``` + +The alert fires the configured webhook (see [Webhooks](#/operations/webhooks)) — useful in CI to catch a misconfigured run before it spends a week of budget overnight. + +## Custom GPU profiles + +To add a GPU not in the default profile: + +```yaml +gpu_profiles: + custom: + - name: "AcmeNVIDIA-XYZ" + pattern: "AcmeNVIDIA-XYZ" # match against nvidia-smi name + memory_gb: 96 + compute_capability: 9.0 + tensor_cores: true +``` + +Drop this in your project root as `gpu_profiles.local.yaml`; ForgeLM auto-merges it. + +## Common pitfalls + +:::warn +**Hourly rate as gospel.** ForgeLM's defaults are reasonable averages — your actual cloud bill depends on instance type, region, spot vs on-demand, and discounts. Override with your real rate. +::: + +:::warn +**Multi-tenancy on shared GPUs.** If multiple jobs share a GPU (rare for training, common for inference), the cost-tracking multiplies rather than divides. Use `--gpus N` to declare actual allocation. +::: + +:::tip +**Track cost over time.** The audit log includes cost for every run; trend it over weeks to catch creeping overruns. A 2× cost increase for the same training time is usually a sign that data grew or hyperparameters drifted. +::: + +## See also + +- [VRAM Fit-Check](#/operations/vram-fit-check) — runs alongside cost estimation. +- [CI/CD Pipelines](#/operations/cicd) — cost alerts in CI. +- [Configuration Reference](#/reference/configuration) — full `cost_tracking` block. diff --git a/docs/usermanuals/en/operations/troubleshooting.md b/docs/usermanuals/en/operations/troubleshooting.md new file mode 100644 index 00000000..a195d57c --- /dev/null +++ b/docs/usermanuals/en/operations/troubleshooting.md @@ -0,0 +1,181 @@ +--- +title: Troubleshooting +description: Common ForgeLM errors and their fixes. +--- + +# Troubleshooting + +This page lists the most common ForgeLM errors and the fixes that work. For anything not listed, run `forgelm doctor` first — it catches 80% of environment problems. + +## Installation issues + +### `bitsandbytes` import error on macOS + +```text +ImportError: bitsandbytes/libbitsandbytes_cpu.so: cannot find ... +``` + +**Cause:** `bitsandbytes` doesn't support Metal/MPS. macOS hosts can't run 4-bit quantised training (QLoRA). + +**Fix:** Either run on Linux with CUDA, or train at full precision (set `model.load_in_4bit: false`). + +### `undefined symbol: __cudaRegisterFatBinaryEnd` + +**Cause:** PyTorch and CUDA toolkit version mismatch. + +**Fix:** Reinstall PyTorch matching your CUDA version: + +```shell +$ pip uninstall torch torchvision torchaudio +$ pip install torch --index-url https://download.pytorch.org/whl/cu121 # match your CUDA +``` + +### `OSError: HuggingFace token not found` + +**Cause:** Some models (Llama, Llama Guard) are gated and require an auth token. + +**Fix:** Run `huggingface-cli login`, or set `HF_TOKEN` environment variable. ForgeLM picks up either. + +## Training issues + +### Loss goes to NaN + +```text +[2026-04-29 14:18:55] training_step_complete loss=nan +``` + +**Causes (most common first):** +1. Learning rate too high (especially with full FT — try 1e-5). +2. Gradient overflow at very low precision (fp16). Switch to bfloat16: `model.bnb_4bit_compute_dtype: "bfloat16"`. +3. Bad data row with extreme tokens (run `forgelm audit` and check for quality flags). +4. Custom reward function returning Inf/NaN (GRPO only). + +### Loss decreases on train, increases on eval + +**Cause:** Overfitting, especially with small datasets and many epochs. + +**Fix:** +- Reduce `epochs` (start with 1-3, not 10). +- Add `neftune_noise_alpha: 5.0` for embedding regularisation. +- Lower learning rate. +- Add more diverse training data. + +### Training crashes at step 0 + +**Cause:** Almost always a configuration problem caught by `--dry-run`. + +**Fix:** Always run `forgelm --config X.yaml --dry-run` before training. The 90% of "training crashed" reports trace back to skipped dry-runs. + +### Training is much slower than expected + +**Causes (most common first):** +1. Not using Unsloth on a supported model (`model.use_unsloth: true` for Qwen / Llama / Mistral). +2. `packing: false` on instruction data (enabling it gives 30-50% throughput). +3. CPU offload accidentally enabled (`distributed.cpu_offload: false`). +4. Mixed-precision misconfigured (use `bfloat16`, not `float16`). +5. Disk I/O bound — your dataset is on slow storage. + +`nvidia-smi` during training: GPU utilization should be >85%. If it's <50%, you're CPU- or I/O-bound, not GPU-bound. + +## OOM errors + +### `CUDA out of memory` mid-training + +**Cause:** Activation memory burst from a particularly long sequence. + +**Fix:** +- Run `--fit-check` to confirm peak estimate. +- Reduce `max_length` if data has long outliers. +- Enable `packing: true` (uniformises sequence length). +- Lower `batch_size` and increase `gradient_accumulation_steps` (same effective batch, less peak). + +### OOM at evaluation, not training + +**Cause:** Eval often runs without sliding-window or packing — peak can exceed training peak. + +**Fix:** Set evaluation `max_length` lower than training: + +```yaml +evaluation: + max_length: 4096 # train at 32K, eval at 4K +``` + +## Data issues + +### `audit refuses to certify a leaky split` + +**Cause:** Train rows also appear in val or test (`cross_split_overlap > 0`). + +**Fix:** Re-split your data, ensuring no document spans multiple splits. See [Cross-Split Leakage](#/data/leakage). + +### Audit reports too many quality flags + +**Cause:** Quality filter is conservative-by-default but can over-flag for code or symbol-heavy data. + +**Fix:** Disable specific checks in YAML: + +```yaml +audit: + quality_filter: + skip: ["min_alpha_ratio", "max_bullet_ratio"] +``` + +### Format auto-detection wrong + +**Cause:** First row of JSONL doesn't match the rest. + +**Fix:** Set format explicitly: `format: "preference"` (or whichever). + +## Eval / safety issues + +### Llama Guard always reports "high severity" + +**Cause:** Probe set contains adversarial inputs the base model already failed on. Llama Guard correctly flags both base and fine-tuned outputs. + +**Fix:** This is correct behaviour. The check that matters is *regression vs baseline*, not absolute scores. Make sure `evaluation.safety.baseline` points at the pre-train baseline. + +### Benchmark scores wildly different from public results + +**Cause:** Likely `num_fewshot` mismatch with the published leaderboard convention. + +**Fix:** Check the canonical setting for each task (e.g. MMLU is canonically 5-shot) and match it. + +## Compliance issues + +### `audit_log.jsonl chain hash invalid` + +**Cause:** The audit log was modified (or the file system corrupted it). + +**Fix:** Don't modify the log. If a corruption happened, the original artifacts are no longer trustworthy — re-run training from a clean state. + +### Annex IV missing required fields + +**Cause:** Required `compliance:` fields not set in YAML. + +**Fix:** Run `forgelm verify-annex-iv path/to/annex_iv.json` for a list of missing fields. + +## Webhooks not firing + +**Causes:** +- Webhook URL points at a private IP and `webhook.allow_private` is false. +- TLS certificate validation fails. +- Endpoint returns 4xx (silent in logs by default). + +**Fix:** Check `audit_log.jsonl` for `webhook_failed` events; they include the response status and body. + +## Where to file a bug + +If `forgelm doctor` says everything's fine but the problem persists, gather: + +1. The exact `forgelm` command that fails. +2. The full error output. +3. Your `config.yaml` (with secrets redacted). +4. Output of `forgelm doctor`. + +Open an issue: . The maintainer team triages within 48 hours. + +## See also + +- [`forgelm doctor`](#/getting-started/installation) — first-line diagnostic. +- [VRAM Fit-Check](#/operations/vram-fit-check) — pre-flight memory check. +- [Configuration Reference](#/reference/configuration) — every YAML field. diff --git a/docs/usermanuals/en/operations/vram-fit-check.md b/docs/usermanuals/en/operations/vram-fit-check.md new file mode 100644 index 00000000..f16ccbfe --- /dev/null +++ b/docs/usermanuals/en/operations/vram-fit-check.md @@ -0,0 +1,142 @@ +--- +title: VRAM Fit-Check +description: Pre-flight memory estimation — fits, tight, OOM, or unknown — before submitting a long job. +--- + +# VRAM Fit-Check + +`--fit-check` runs a static analysis of your config and reports whether peak VRAM will fit the available GPU. No training happens, no data is loaded — it just answers the question "will this OOM?" in seconds. + +## Quick example + +```shell +$ forgelm --config configs/customer-support.yaml --fit-check +FITS est. peak 11.4 GB / 12 GB available + +Components: + Model weights (4-bit): 3.8 GB + KV cache (max_length=4096): 1.4 GB + Activations (batch=2): 2.6 GB + Optimizer state (LoRA): 1.3 GB + Reference model (DPO): 1.9 GB ← would OOM without QLoRA + Buffer (10%): 0.4 GB + ------- + Total estimated peak: 11.4 GB + +Recommendations: none — this configuration fits. +``` + +## Verdicts + +| Verdict | Meaning | Action | +|---|---|---| +| `FITS` | Comfortably within VRAM. | Proceed. | +| `TIGHT` | Within VRAM but no headroom for activation bursts. | Reduce `max_length` or batch size. | +| `OOM` | Will not fit. | Apply suggested fixes. | +| `UNKNOWN` | GPU profile not in database. | Train conservatively; report to GitHub Issues. | + +## What `OOM` looks like + +```text +$ forgelm --config configs/large-context.yaml --fit-check +OOM est. peak 32.4 GB / 24 GB available + +Components: + Model weights (full prec): 14.2 GB + KV cache (max_length=32768): 6.8 GB ← biggest contributor + ... + +Suggested fixes (any one usually resolves): + 1. Enable QLoRA: model.load_in_4bit: true (saves ~10 GB) + 2. Reduce max_length: 32768 → 8192 (saves ~5 GB) + 3. Reduce batch_size: 4 → 2 (saves ~2 GB) + 4. Switch to SimPO from DPO (no ref model) (saves ~10 GB) + 5. Enable distributed.zero_stage: 2 (multi-GPU) +``` + +## What components are estimated + +| Component | Depends on | +|---|---| +| Model weights | Model size + precision (full / 8-bit / 4-bit) | +| KV cache | `max_length` × hidden dim × layers × heads | +| Activations | `batch_size` × `max_length` × hidden dim | +| Gradients | Model size × precision (or LoRA rank if PEFT) | +| Optimizer state | Adam: 2× model size × precision; LoRA: 2× rank × ... | +| Reference model | DPO/KTO only — full copy of model | +| Reward model | GRPO only | +| Activation memory peaks | Estimated from architecture-specific patterns | +| Buffer | 10% safety margin | + +## How accurate is it? + +Empirically, `--fit-check` is correct ~95% of the time. The 5% failures are usually: + +- Unusual model architectures (MoE with sparse expert routing). +- Sample packing with very high token efficiency (better than expected). +- DeepSpeed offload configurations (lower than expected). + +For peace of mind on borderline cases, the verdict displays an estimate range with confidence: + +```text +TIGHT est. peak 21.8 GB / 24 GB (95% confidence: 19.4 - 23.9 GB) +``` + +If the upper end of the confidence range exceeds available VRAM, treat the run as OOM-likely. + +## Multi-GPU + +For distributed training, fit-check accounts for sharding: + +```shell +$ forgelm --config configs/zero3.yaml --fit-check --gpus 4 +FITS est. peak 14.2 GB / 80 GB per GPU (sharded across 4) + +ZeRO-3 sharding: + Optimizer state: 1/4 per GPU + Gradients: 1/4 per GPU + Parameters: 1/4 per GPU +``` + +## Programmatic API + +For dashboards or automation: + +```python +from forgelm.fit_check import estimate_peak_memory, available_memory + +estimate = estimate_peak_memory(config_path="configs/run.yaml") +available = available_memory() +print(f"Verdict: {estimate.verdict}") +print(f"Peak: {estimate.peak_gb:.1f} GB / {available.total_gb:.1f} GB available") +``` + +## When --fit-check is wrong + +Edge cases where the estimate is off: + +- **Unusual MoE routing.** Some MoE models have load patterns the estimator doesn't model. Run a short calibration training and compare actual peak. +- **CPU offload.** ZeRO-3 with `offload_param: cpu` reduces VRAM unpredictably; estimate is conservative (over-estimates VRAM use). +- **Very long sequences** (>64K). The `O(N²)` attention term dominates; small differences in implementation matter. + +For these cases, run with `--fit-check-strict` which uses the worst-case estimate and reports `TIGHT` even when the median estimate says `FITS`. + +## Common pitfalls + +:::warn +**Skipping fit-check on "I think this fits" runs.** A 5-minute fit-check saves you from a 6-hour OOM 6 hours into training. Always run it. +::: + +:::warn +**Running with `TIGHT` verdict.** Tight runs OOM intermittently — the first few epochs fit, then a particularly long sequence triggers an activation burst. Either reduce something or be ready for crashes. +::: + +:::tip +**Fit-check before --dry-run.** Order matters: dry-run downloads the model (slow); fit-check is a static analysis (fast). If fit-check says OOM, you've saved the download. Always run fit-check first. +::: + +## See also + +- [GPU Cost Estimation](#/operations/gpu-cost) — sister pre-flight check. +- [Distributed Training](#/training/distributed) — for when single-GPU OOMs. +- [LoRA, QLoRA, DoRA](#/training/lora) — common OOM remedy. diff --git a/docs/usermanuals/en/operations/webhooks.md b/docs/usermanuals/en/operations/webhooks.md new file mode 100644 index 00000000..1d273172 --- /dev/null +++ b/docs/usermanuals/en/operations/webhooks.md @@ -0,0 +1,159 @@ +--- +title: Webhooks +description: Slack and Teams notifications on training events — start, success, failure, auto-revert. +--- + +# Webhooks + +ForgeLM fires structured webhooks on training milestones. Wire them into Slack, Teams, or any incident tool that accepts JSON payloads — get the right context to the right humans without anyone watching a log. + +## Quick example + +```yaml +output: + webhook: + url: "${SLACK_WEBHOOK}" + events: ["run_start", "auto_revert", "run_complete", "run_failed"] + template: "slack" # or teams, generic +``` + +ForgeLM picks up `${SLACK_WEBHOOK}` from environment variables. Common pattern: + +```shell +$ export SLACK_WEBHOOK="https://hooks.slack.com/services/T.../B.../..." +$ forgelm --config configs/run.yaml +``` + +## Events you can subscribe to + +| Event | When fired | +|---|---| +| `run_start` | Training kicks off. | +| `data_audit_complete` | After `forgelm audit`. | +| `training_epoch_complete` | After each epoch. (verbose; usually skipped) | +| `benchmark_complete` | After eval suite. | +| `safety_eval_complete` | After Llama Guard scoring. | +| `auto_revert` | When auto-revert triggers. | +| `human_approval_request` | When `compliance.human_approval` blocks. | +| `human_approval_granted` | When approval is signed. | +| `model_exported` | After `forgelm export`. | +| `run_complete` | Successful exit. | +| `run_failed` | Non-zero exit. | + +Subscribe selectively — too-frequent webhooks become spam. + +## Payload shape + +Generic format (the `slack` and `teams` templates wrap this in their respective formats): + +```json +{ + "event": "auto_revert", + "ts": "2026-04-29T14:33:04Z", + "run_id": "abc123", + "config_path": "configs/customer-support.yaml", + "trigger": "safety_regression", + "regressed_categories": ["S5"], + "details": {...}, + "artifacts_url": "https://compliance-store.example/abc123/" +} +``` + +## Slack template + +```yaml +output: + webhook: + url: "${SLACK_WEBHOOK}" + template: "slack" + events: ["run_complete", "run_failed", "auto_revert"] + channel: "#ml-training" # optional override + mention_on_failure: "@ml-oncall" +``` + +Produces: + +```text +🔥 ForgeLM auto-revert triggered + +Run: customer-support v1.2.0 (abc123) +Trigger: safety_regression in S5 +Restored from: checkpoints/sft-base +Audit log: artifacts/audit_log.jsonl + +@ml-oncall please investigate. +``` + +## Microsoft Teams template + +```yaml +output: + webhook: + url: "${TEAMS_WEBHOOK}" + template: "teams" + events: ["auto_revert", "human_approval_request"] +``` + +Produces a Teams MessageCard with the same data formatted as a card with action buttons. + +## Generic template (custom integrations) + +For your own dashboard, incident system, or pipeline: + +```yaml +output: + webhook: + url: "https://internal.example/forgelm-events" + template: "generic" + events: ["run_start", "run_complete", "run_failed", "auto_revert"] + headers: + Authorization: "Bearer ${INCIDENT_API_TOKEN}" + timeout_seconds: 5 + retries: 3 +``` + +The endpoint receives the raw structured payload above. ForgeLM POSTs JSON, expects 2xx, retries on transient failures. + +## Multiple destinations + +To send different events to different places: + +```yaml +output: + webhooks: + - url: "${SLACK_WEBHOOK}" + template: "slack" + events: ["run_complete", "run_failed"] + - url: "${PAGERDUTY_WEBHOOK}" + template: "generic" + events: ["auto_revert"] # critical only + - url: "${INTERNAL_DASHBOARD_URL}" + template: "generic" + events: ["*"] # everything for the dashboard +``` + +## Security considerations + +- **TLS only.** ForgeLM rejects HTTP webhook URLs in production builds. +- **Sensitive data redaction.** API keys, full configs, and PII in payloads are redacted by default. Override with `webhook.redact: false` only if you control both endpoints. +- **Server-Side Request Forgery (SSRF) guard.** ForgeLM blocks webhook URLs pointing at internal IPs (RFC 1918, link-local) unless you explicitly allow them with `webhook.allow_private: true`. This prevents misconfigured runs from probing your internal network. + +## Common pitfalls + +:::warn +**Webhook silently failing.** A 4xx response from the webhook endpoint shouldn't fail the training run, but ForgeLM also shouldn't silently swallow the error. Check `audit_log.jsonl` for `webhook_failed` events; investigate why your endpoint rejected. +::: + +:::warn +**Subscribing to `training_epoch_complete`.** For a 50-epoch training run, that's 50 messages — Slack will rate-limit you. Use `run_start` and `run_complete` for the bookends. +::: + +:::tip +**Test webhooks with `--webhook-test`.** Before going live, run `forgelm --config X.yaml --webhook-test` — it fires a synthetic payload to your webhook so you can verify the formatting. No actual training happens. +::: + +## See also + +- [CI/CD Pipelines](#/operations/cicd) — the natural home of webhooks. +- [Auto-Revert](#/evaluation/auto-revert) — produces the most actionable webhook. +- [Human Oversight](#/compliance/human-oversight) — webhook-driven approval flow. diff --git a/docs/usermanuals/en/reference/cli.md b/docs/usermanuals/en/reference/cli.md new file mode 100644 index 00000000..fb39f777 --- /dev/null +++ b/docs/usermanuals/en/reference/cli.md @@ -0,0 +1,219 @@ +--- +title: CLI Reference +description: Every forgelm subcommand and flag, with auth setup and common patterns. +--- + +# CLI Reference + +ForgeLM ships a single `forgelm` binary with subcommands. This page is the canonical reference; for tutorial-level guidance, see [Your First Run](#/getting-started/first-run). + +## Top-level subcommands + +| Command | What it does | +|---|---| +| `forgelm` (no subcommand) | Train (with `--config`). | +| `forgelm doctor` | Environment check — Python, CUDA, GPU, deps. | +| `forgelm quickstart` | List or instantiate bundled templates. | +| `forgelm ingest` | PDF/DOCX/EPUB → JSONL conversion. | +| `forgelm audit` | Pre-train data audit. | +| `forgelm benchmark` | Run lm-eval-harness against a model. | +| `forgelm safety-eval` | Llama Guard scoring. | +| `forgelm chat` | Interactive REPL. | +| `forgelm batch-chat` | Non-interactive prompt → response. | +| `forgelm export` | GGUF export with quantisation. | +| `forgelm deploy` | Generate deployment config (Ollama, vLLM, TGI, etc). | +| `forgelm verify-annex-iv` | Validate an Annex IV artifact. | +| `forgelm verify-log` | Validate audit log chain. | +| `forgelm verify-gguf` | Validate GGUF integrity. | +| `forgelm cache-models` | Pre-cache HuggingFace models for air-gap. | +| `forgelm cache-tasks` | Pre-cache lm-evaluation-harness tasks. | +| `forgelm trend` | Show metric trends across recent runs. | +| `forgelm compare-runs` | Side-by-side comparison of run metrics. | +| `forgelm approve` | Sign a human approval request. | +| `forgelm approvals` | List pending approvals. | + +Run `forgelm --help` for any of these. + +## Top-level flags (apply across many subcommands) + +| Flag | Description | +|---|---| +| `--config PATH` | YAML config file path. Required for training. | +| `--dry-run` | Validate config and references; no training. | +| `--fit-check` | Estimate VRAM and report verdict; no training. | +| `--estimate-cost` | Pre-flight cost estimate; no training. | +| `--offline` | Disable all network calls; require everything cached. | +| `--output-format {plain,json}` | Logging format. JSON for CI. | +| `--verbose, -v` | Increase logging detail. | +| `--quiet, -q` | Reduce logging detail. | +| `--version` | Print version. | +| `--help, -h` | Show help. | + +## Training: `forgelm` + +Most-used patterns: + +```shell +$ forgelm --config configs/run.yaml --dry-run # validate +$ forgelm --config configs/run.yaml --fit-check # VRAM check +$ forgelm --config configs/run.yaml # train +$ forgelm --config configs/run.yaml --resume # resume from last checkpoint +$ forgelm --config configs/run.yaml --merge # run as a merge job +$ forgelm --config configs/run.yaml --generate-data # synthetic data only +``` + +Resume from a specific checkpoint: `--resume-from PATH`. + +## Audit: `forgelm audit` + +```shell +$ forgelm audit DATAFILE_OR_DIR \ + [--output ./audit/] \ + [--strict] \ + [--dedup-algo simhash|minhash] \ + [--dedup-threshold N] \ + [--skip-pii] [--skip-secrets] [--skip-quality] [--skip-leakage] \ + [--remove-duplicates] [--remove-cross-split-overlap=val|test] \ + [--output-clean PATH] \ + [--show-leakage] \ + [--sample-rate FLOAT] +``` + +See [Dataset Audit](#/data/audit) for full semantics. + +## Ingest: `forgelm ingest` + +```shell +$ forgelm ingest INPUT_DIR \ + --output PATH.jsonl \ + [--recursive] \ + [--strategy tokens|markdown|paragraph|sentence] \ + [--max-tokens N] [--overlap N] \ + [--pii-mask] [--secrets-mask] \ + [--pii-locale tr|de|fr|us] \ + [--language LANG] \ + [--include "*.pdf,*.md"] [--exclude "drafts/*"] \ + [--format raw|instructions|qa] +``` + +See [Document Ingestion](#/data/ingestion). + +## Chat: `forgelm chat` + +```shell +$ forgelm chat CHECKPOINT \ + [--base BASE_MODEL] \ + [--temperature 0.7] [--top-p 0.9] [--max-tokens 1024] \ + [--system "system prompt"] \ + [--safety on|off] \ + [--load PATH] # load saved session +``` + +Slash commands within the REPL: `/reset`, `/save`, `/load`, `/system`, `/temperature`, `/top_p`, `/max_tokens`, `/safety`, `/help`, `/quit`. See [Interactive Chat](#/deployment/chat). + +## Export: `forgelm export` + +```shell +$ forgelm export CHECKPOINT_DIR \ + --output PATH.gguf \ + --quant q4_k_m|q5_k_m|q6_k|q8_0|q3_k_m|q2_k|fp16 \ + [--merge] # merge LoRA into base before export +``` + +Comma-separate `--quant` for multiple levels in one command. See [GGUF Export](#/deployment/gguf-export). + +## Deploy: `forgelm deploy` + +```shell +$ forgelm deploy CHECKPOINT_DIR \ + --target ollama|vllm|tgi|hf-endpoints|kserve|triton \ + --output PATH_OR_DIR +``` + +See [Deploy Targets](#/deployment/deploy-targets). + +## Authentication + +ForgeLM picks up credentials from environment variables. Never put them in YAML. + +| Provider | Env var | Used for | +|---|---|---| +| HuggingFace | `HF_TOKEN` | Gated models (Llama, Llama Guard) | +| OpenAI | `OPENAI_API_KEY` | LLM-as-judge, synthetic data | +| Anthropic | `ANTHROPIC_API_KEY` | LLM-as-judge, synthetic data | +| W&B | `WANDB_API_KEY` | Experiment tracking | +| Cohere | `COHERE_API_KEY` | (synthetic data) | + +YAML interpolation: + +```yaml +auth: + hf_token: "${HF_TOKEN}" +synthetic: + teacher: + api_key: "${OPENAI_API_KEY}" +``` + +If the env var isn't set, ForgeLM fails at config load with a clear error — better than crashing 6 hours into training because of a missing token. + +## Exit codes + +| Exit | Meaning | +|---|---| +| 0 | Success | +| 1 | Config / arg error | +| 2 | Audit warnings (with `--strict`) | +| 3 | Auto-revert / regression | +| 4 | Awaiting human approval | +| 130 | User interrupted (Ctrl+C) | + +See [Exit Codes](#/reference/exit-codes) for the full contract. + +## Environment variables + +| Variable | What it sets | +|---|---| +| `HF_TOKEN` | HuggingFace auth | +| `HF_HOME` | HuggingFace cache directory (default `~/.cache/huggingface`) | +| `HF_HUB_OFFLINE=1` | Disable HF Hub network calls | +| `TRANSFORMERS_OFFLINE=1` | Disable transformers library network calls | +| `HF_DATASETS_OFFLINE=1` | Disable datasets library network calls | +| `FORGELM_CACHE_DIR` | ForgeLM-specific cache location | +| `FORGELM_LOG_LEVEL` | Override logging level (DEBUG, INFO, WARN, ERROR) | +| `FORGELM_RESUME_TOKEN` | Token for the API-based human approval flow | + +## Common patterns + +### "Just train and don't bother me" + +```shell +$ forgelm --config configs/run.yaml --output-format json | tee run.log +``` + +### "Run audit, then train if clean" + +```shell +$ forgelm audit data/ --strict && forgelm --config configs/run.yaml +``` + +### "Train, export GGUF, deploy to Ollama" + +```yaml +# configs/run.yaml +output: + gguf: + enabled: true +deployment: + target: ollama +``` + +```shell +$ forgelm --config configs/run.yaml +# Training, export, and deploy config generation all happen. +``` + +## See also + +- [Configuration Reference](#/reference/configuration) — YAML companion. +- [Exit Codes](#/reference/exit-codes) — gate contract for CI. +- [YAML Templates](#/reference/yaml-templates) — full working configs. diff --git a/docs/usermanuals/en/reference/configuration.md b/docs/usermanuals/en/reference/configuration.md new file mode 100644 index 00000000..35dc2140 --- /dev/null +++ b/docs/usermanuals/en/reference/configuration.md @@ -0,0 +1,318 @@ +--- +title: Configuration Reference +description: Every YAML field ForgeLM understands, with types, defaults, and notes. +--- + +# Configuration Reference + +This is the canonical reference for every YAML field ForgeLM accepts. The schema is enforced by Pydantic; running `forgelm --config X.yaml --dry-run` validates your file against it. + +The top-level config has 13 blocks: + +```yaml +model: {...} +lora: {...} +galore: {...} +datasets: [...] +training: {...} +evaluation: {...} +synthetic: {...} +merge: {...} +distributed: {...} +compliance: {...} +output: {...} +auth: {...} +deployment: {...} +``` + +## `model:` + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" # HF id or local path (required) + trust_remote_code: false # only set true if you trust the model's repo + max_length: 4096 # context for training + load_in_4bit: false # QLoRA toggle + load_in_8bit: false + bnb_4bit_quant_type: "nf4" # nf4 | fp4 + bnb_4bit_compute_dtype: "bfloat16" # bfloat16 | float16 | float32 + use_unsloth: false # 2-5× speedup on supported models + attention_implementation: "auto" # auto | flash_attention_2 | sdpa | eager + rope_scaling: # see [Long-Context](#/training/long-context) + type: "linear" # linear | dynamic | yarn | longrope + factor: 4.0 + sliding_window: null # int — sliding window for long context + torch_dtype: "auto" # auto-pick based on quantisation +``` + +## `lora:` + +```yaml +lora: + r: 16 # rank — see [LoRA](#/training/lora) + alpha: 32 + dropout: 0.05 + target_modules: ["q_proj", "k_proj", "v_proj", "o_proj"] + modules_to_save: [] # full-precision modules (e.g. embeddings) + use_dora: false # DoRA variant + use_pissa: false # PiSSA initialisation + use_rslora: false # rsLoRA scaling +``` + +## `galore:` (alternative to `lora:`) + +```yaml +galore: + enabled: false # incompatible with lora.r when true + rank: 256 + update_proj_gap: 200 + scale: 0.25 + proj_type: "std" # std | reverse_std | right | left + target_modules: ["attn", "mlp"] +``` + +## `datasets:` + +```yaml +datasets: + - path: "data/train.jsonl" # required + format: "messages" # auto-detected if omitted + weight: 1.0 # mixing weight; sum across all datasets + split: "train" # train | val | test + streaming: false +``` + +Multiple datasets allowed. Format options: `instructions`, `messages`, `preference`, `binary`, `reward`. See [Dataset Formats](#/concepts/data-formats). + +## `training:` + +```yaml +training: + trainer: "sft" # sft | dpo | simpo | kto | orpo | grpo + epochs: 3 + max_steps: -1 # -1 means use epochs + batch_size: 4 + gradient_accumulation_steps: 1 + learning_rate: 2.0e-4 + scheduler: "cosine" # cosine | linear | constant | warmup_cosine + warmup_ratio: 0.03 + weight_decay: 0.0 + optimizer: "adamw_8bit" # adamw | adamw_8bit | galore_adamw_8bit + seed: 42 + packing: false + neftune_noise_alpha: null # float — embedding noise regularisation + loss_on_completions_only: true # SFT-specific + log_grad_norm: false + report_to: ["tensorboard"] # see [Experiment Tracking](#/operations/experiment-tracking) + run_name: null # auto-generated from config hash + tags: [] + notes: null + + # Trainer-specific blocks + dpo: { beta: 0.1, loss_type: "sigmoid", reference_free: false } + simpo: { beta: 2.0, gamma: 1.0, length_normalize: true } + kto: { beta: 0.1, desirable_weight: 1.0, undesirable_weight: 1.0 } + orpo: { beta: 0.1, sft_weight: 1.0 } + grpo: + group_size: 8 + beta: 0.04 + reward_function: "my_module.score" + format_reward: 0.2 + answer_pattern: null + temperature: 0.9 +``` + +## `evaluation:` + +```yaml +evaluation: + enabled: true + max_length: null # null = same as training + benchmark: + enabled: false + tasks: [] + floors: {} + num_fewshot: 0 + batch_size: 8 + limit: null + safety: + enabled: false + model: "meta-llama/Llama-Guard-3-8B" + block_categories: [] + test_prompts: null # null = built-in default probes + severity_threshold: "medium" # low | medium | high | critical + regression_tolerance: 0.05 + baseline: null + judge: + enabled: false + mode: "pairwise" # pairwise | single-rubric | elo + judge_model: + provider: "openai" + model: "gpt-4o-mini" + baseline_model: null + test_prompts: null + num_samples: 200 + rubric: "default" + self_consistency: 1 + swap_positions: true + budget_usd: null + trend: + enabled: false + history_file: ".forgelm/eval-history.jsonl" + lookback_runs: 10 + drift_p_threshold: 0.05 + fail_on_concern: "high" + auto_revert: + enabled: false + last_good_checkpoint: null + notify_on_revert: true + keep_failed_checkpoint: true + guards: {} # custom callable guards +``` + +## `synthetic:` + +```yaml +synthetic: + enabled: false + teacher: + provider: "openai" # openai | anthropic | local | vllm + model: "gpt-4o" + api_key: "${OPENAI_API_KEY}" + seed_prompts: "data/seeds.jsonl" + output: "data/synthetic.jsonl" + num_samples: 1000 + temperature: 0.7 + prompt_template: "default" + budget_usd: null + rate_limit: + requests_per_minute: 100 + burst: 10 +``` + +## `merge:` + +```yaml +merge: + enabled: false + algorithm: "ties" # linear | slerp | ties | dare | dare_ties + base_model: null # required when enabled + models: + - path: "./checkpoints/v1" + weight: 0.5 + parameters: + threshold: 0.7 # TIES + density: 0.7 # DARE + t: 0.5 # SLERP + output: + dir: "./checkpoints/merged" + model_card: true +``` + +## `distributed:` + +```yaml +distributed: + strategy: "single" # single | deepspeed | fsdp + zero_stage: null # 2 | 3 (when strategy=deepspeed) + cpu_offload: false + nvme_offload_path: null + fsdp_state_dict_type: "FULL_STATE_DICT" + fsdp_auto_wrap_policy: "TRANSFORMER_BASED_WRAP" + fsdp_offload_params: false + gradient_accumulation_steps: 1 +``` + +## `compliance:` + +```yaml +compliance: + annex_iv: false + data_audit_artifact: null + human_approval: false + intended_purpose: null # required if annex_iv: true + risk_classification: null # required if annex_iv: true + deployment_geographies: [] + responsible_party: null + version: null + standards: [] + notes: null + risk_assessment: + foreseeable_misuse: [] + mitigations: [] + residual_risks: [] + data_protection: + framework: null # GDPR | KVKK | both + lawful_basis: null + purpose: null + data_controller: null + international_transfers: + enabled: false + safeguards: null + audit_log: + enabled: false + path: "${output.dir}/artifacts/audit_log.jsonl" + forward_to: [] + approval: + request_webhook: null + signature_method: "cli" + timeout_hours: 48 + require_role: null + quorum: 1 + post_market_plan: null + license: "Apache-2.0" +``` + +## `output:` + +```yaml +output: + dir: "./checkpoints/run" # required + model_card: true + save_format: "safetensors" # safetensors | pytorch + save_strategy: "epoch" # epoch | steps | no + save_steps: 500 + webhook: # see [Webhooks](#/operations/webhooks) + url: null + template: "slack" + events: [] + cost_tracking: + enabled: false + rate_per_hour: {} + currency: "USD" + alert_threshold_usd: null + halt_threshold_usd: null + gguf: + enabled: false + quant_levels: ["q4_k_m"] + output_dir: "${output.dir}/gguf/" + manifest: true +``` + +## `auth:` + +```yaml +auth: + hf_token: null # ${HF_TOKEN} via env (preferred) + openai_api_key: null + anthropic_api_key: null +``` + +## `deployment:` + +```yaml +deployment: + target: null # ollama | vllm | tgi | hf-endpoints | kserve | triton + served_model_name: null + max_input_length: 4096 + max_total_tokens: 8192 + gpu_memory_utilization: 0.85 + chat_template: null + system_prompt_default: null +``` + +## See also + +- [CLI Reference](#/reference/cli) — flags that complement YAML fields. +- [YAML Templates](#/reference/yaml-templates) — full working examples. +- [Configuration Overview (concepts)](#/concepts/alignment-overview) — what these fields mean conceptually. diff --git a/docs/usermanuals/en/reference/exit-codes.md b/docs/usermanuals/en/reference/exit-codes.md new file mode 100644 index 00000000..e3ca35d9 --- /dev/null +++ b/docs/usermanuals/en/reference/exit-codes.md @@ -0,0 +1,134 @@ +--- +title: Exit Codes +description: ForgeLM's exit-code contract — the public API for CI/CD pipelines. +--- + +# Exit Codes + +ForgeLM's exit codes are a public contract. CI/CD pipelines, schedulers, and dashboards depend on them. They will not silently change between releases. + +## The contract + +| Exit | Name | Meaning | Typical CI action | +|---|---|---|---| +| **0** | Success | Run completed; all gates passed; checkpoint promoted. | Continue pipeline | +| **1** | Config error | YAML invalid, file missing, env var unset, or argument malformed. | Fail fast | +| **2** | Audit warnings | Audit ran with `--strict` and reported warning-level issues. | Block merge / require review | +| **3** | Regression / auto-revert | Benchmark or safety gate failed; auto-reverted. | Investigate; do NOT promote | +| **4** | Awaiting human approval | `compliance.human_approval: true` blocking. | Hold pipeline; trigger reviewer | +| **5** | Cost ceiling exceeded | `output.cost_tracking.halt_threshold_usd` crossed. | Investigate cost overrun | +| **130** | Interrupted | User pressed Ctrl+C. | Manual decision | + +Any other non-zero exit indicates an unexpected error — file an issue. + +## Mapping to CI patterns + +### GitHub Actions + +```yaml +- name: Train + id: train + run: forgelm --config configs/run.yaml + continue-on-error: true + +- name: Block on regression + if: steps.train.outcome == 'failure' && steps.train.conclusion == 'failure' + run: | + if [ "${{ steps.train.outputs.exit-code }}" = "3" ]; then + echo "::error::Regression detected — see audit log" + exit 1 + fi +``` + +For most pipelines, the simpler pattern is fine: + +```yaml +- name: Train + run: forgelm --config configs/run.yaml + # Any non-zero exit fails the step. The artifact upload step still runs (if: always()). +``` + +### GitLab CI + +```yaml +train: + script: + - forgelm --config configs/run.yaml + allow_failure: + exit_codes: [4] # exit 4 (waiting for approval) doesn't fail CI +``` + +### Jenkins + +```groovy +stage('Train') { + steps { + script { + def status = sh(script: 'forgelm --config configs/run.yaml', returnStatus: true) + if (status == 4) { + currentBuild.result = 'UNSTABLE' // hold for approval + } else if (status != 0) { + error "Training failed with exit code ${status}" + } + } + } +} +``` + +## When to use each exit code + +| Situation | What ForgeLM exits with | +|---|---| +| YAML has typo (e.g. `learnng_rate`) | 1 | +| `${HF_TOKEN}` set in YAML but env var missing | 1 | +| `--config` points to non-existent file | 1 | +| Audit with `--strict` and PII flags | 2 | +| Audit with `--strict` and cross-split leakage | 3 (cross-split is error, not warning) | +| DPO run, Llama Guard S5 regressed beyond tolerance | 3 | +| Benchmark hellaswag dropped below floor | 3 | +| Final loss is NaN | 3 | +| `compliance.human_approval: true` and no approval signed | 4 | +| Cost threshold crossed mid-training | 5 | +| User Ctrl+C | 130 | + +## Programmatic determination + +For automated parsing, ForgeLM also writes the exit code to a sidecar file: + +```text +checkpoints/run/artifacts/exit_status.txt: + +3 +trigger=safety_regression +regressed_categories=S5 +restored_from=./checkpoints/sft-base +``` + +This is helpful when CI runners stream output to log aggregation that doesn't preserve raw exit codes (some Jenkins setups, certain GitOps tools). The sidecar is always written. + +## What "exit 0" actually guarantees + +A run that exits 0 has: +- Validated config without errors. +- Loaded the model and dataset. +- Completed all configured training steps. +- Passed every configured benchmark floor. +- Passed every configured safety threshold. +- Written the model card. +- Written the Annex IV bundle (if configured). +- Written manifest.json with SHA-256 over all artifacts. +- Optionally: written GGUF, deployment config. +- Closed the audit log with `run_complete`. + +If any of these failed, the exit code is non-zero. There is no "partial success" exit code by design. + +## Compatibility guarantee + +Exit codes 0-5 are stable across versions. New codes may be added (6, 7, ...) but existing ones won't change semantics. CI pipelines pinned to the contract above will continue working across ForgeLM upgrades. + +## See also + +- [CI/CD Pipelines](#/operations/cicd) — patterns that use this contract. +- [CLI Reference](#/reference/cli) — every command that emits these codes. +- [Auto-Revert](#/evaluation/auto-revert) — produces exit 3. +- [Human Oversight](#/compliance/human-oversight) — produces exit 4. diff --git a/docs/usermanuals/en/reference/yaml-templates.md b/docs/usermanuals/en/reference/yaml-templates.md new file mode 100644 index 00000000..c5bb13f9 --- /dev/null +++ b/docs/usermanuals/en/reference/yaml-templates.md @@ -0,0 +1,356 @@ +--- +title: YAML Templates +description: Full working configurations for common workflows — copy, adapt, run. +--- + +# YAML Templates + +These templates are tested as part of CI. Copy any of them, change the names and paths, and run. + +## Customer-support assistant (SFT → DPO) + +A multi-turn helpful + safe model, the most common production pattern. + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true + max_length: 4096 + +lora: + r: 16 + alpha: 32 + use_dora: true + +datasets: + - path: "data/customer-support-sft.jsonl" + format: "messages" + - path: "data/customer-support-prefs.jsonl" + format: "preference" + split: "train" + +training: + trainer: "dpo" + epochs: 1 + batch_size: 2 + gradient_accumulation_steps: 8 + learning_rate: 5.0e-6 + scheduler: "cosine" + warmup_ratio: 0.05 + packing: true + dpo: + beta: 0.1 + loss_type: "sigmoid" + report_to: ["tensorboard"] + +evaluation: + benchmark: + enabled: true + tasks: ["hellaswag", "arc_easy", "truthfulqa"] + floors: + hellaswag: 0.55 + arc_easy: 0.70 + truthfulqa: 0.45 + safety: + enabled: true + model: "meta-llama/Llama-Guard-3-8B" + block_categories: ["S1", "S2", "S5", "S10"] + severity_threshold: "medium" + auto_revert: + enabled: true + +compliance: + annex_iv: true + data_audit_artifact: "./audit/data_audit_report.json" + human_approval: true + intended_purpose: "Customer-support assistant for a Turkish telecom" + risk_classification: "high-risk" + deployment_geographies: ["TR", "EU"] + responsible_party: "Acme Corp " + version: "1.2.0" + +output: + dir: "./checkpoints/customer-support-v1.2" + model_card: true + webhook: + url: "${SLACK_WEBHOOK}" + template: "slack" + events: ["run_complete", "run_failed", "auto_revert"] + gguf: + enabled: true + quant_levels: ["q4_k_m"] + +deployment: + target: "ollama" +``` + +## Domain expert from PDFs (SFT only) + +For the "fine-tune on our internal documentation" use case. + +```yaml +# After running: +# forgelm ingest ./regulatory-docs/ --recursive --strategy markdown \ +# --pii-mask --secrets-mask --output data/regulatory.jsonl +# forgelm audit data/regulatory.jsonl + +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true + max_length: 8192 + +lora: + r: 32 + alpha: 64 + +datasets: + - path: "data/regulatory.jsonl" + format: "instructions" + +training: + trainer: "sft" + epochs: 3 + batch_size: 2 + gradient_accumulation_steps: 16 + learning_rate: 2.0e-4 + scheduler: "cosine" + warmup_ratio: 0.03 + packing: true + neftune_noise_alpha: 5.0 + +evaluation: + benchmark: + enabled: true + tasks: ["mmlu"] + floors: { mmlu: 0.48 } + safety: + enabled: true + block_categories: ["S5", "S6"] # defamation + specialised advice + +compliance: + annex_iv: true + intended_purpose: "Regulatory Q&A assistant for compliance team" + risk_classification: "high-risk" + deployment_geographies: ["EU", "TR"] + responsible_party: "Acme Compliance Team" + +output: + dir: "./checkpoints/regulatory-qa" +``` + +## GRPO math reasoning + +```yaml +model: + name_or_path: "./checkpoints/sft-base" # SFT first, GRPO second + max_length: 4096 + +lora: + r: 16 + alpha: 32 + +datasets: + - path: "data/math-problems.jsonl" + format: "reward" + +training: + trainer: "grpo" + epochs: 1 + batch_size: 1 + gradient_accumulation_steps: 4 + learning_rate: 1.0e-6 + scheduler: "constant" + grpo: + group_size: 8 + beta: 0.04 + reward_function: "rewards.math_score" + format_reward: 0.2 + answer_pattern: "\\boxed\\{(.*?)\\}" + temperature: 0.9 + +evaluation: + benchmark: + enabled: true + tasks: ["gsm8k"] + floors: { gsm8k: 0.55 } + +output: + dir: "./checkpoints/math-grpo" +``` + +```python +# rewards.py +def math_score(prompt: str, response: str, ground_truth: str) -> float: + import re + m = re.search(r'\\boxed\{(.*?)\}', response) + if not m: + return -0.5 + try: + return 1.0 if float(m.group(1)) == float(ground_truth) else -1.0 + except ValueError: + return -0.5 +``` + +## Multi-GPU 70B with ZeRO-3 + +For training a 70B model across 8× A100 80GB. + +```yaml +model: + name_or_path: "meta-llama/Llama-3.1-70B-Instruct" + max_length: 4096 + attention_implementation: "flash_attention_2" + +lora: + r: 32 + alpha: 64 + +datasets: + - path: "data/train.jsonl" + format: "messages" + +training: + trainer: "sft" + epochs: 2 + batch_size: 1 + gradient_accumulation_steps: 16 + learning_rate: 1.0e-4 + scheduler: "cosine" + +distributed: + strategy: "deepspeed" + zero_stage: 3 + cpu_offload: false # all 8 A100s have plenty + +evaluation: + benchmark: + enabled: true + tasks: ["mmlu"] + floors: { mmlu: 0.65 } + +output: + dir: "./checkpoints/llama-70b-finetune" +``` + +Launch: `accelerate launch --num_processes 8 -m forgelm --config configs/llama-70b.yaml` + +## Synthetic data + SFT + +Distil GPT-4o into a 7B student. + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true + max_length: 4096 + +datasets: + - path: "data/seed-prompts.jsonl" + format: "instructions" + - path: "data/synthetic.jsonl" # generated by --generate-data + format: "instructions" + +training: + trainer: "sft" + epochs: 2 + learning_rate: 2.0e-4 + +synthetic: + enabled: true + teacher: + provider: "openai" + model: "gpt-4o" + api_key: "${OPENAI_API_KEY}" + seed_prompts: "data/seed-prompts.jsonl" + output: "data/synthetic.jsonl" + num_samples: 5000 + temperature: 0.7 + budget_usd: 50.0 + +output: + dir: "./checkpoints/distilled" +``` + +Run: + +```shell +$ forgelm --config configs/distill.yaml --generate-data # creates data/synthetic.jsonl +$ forgelm --config configs/distill.yaml # trains on seeds + synthetic +``` + +## Model merging + +Merge three specialist LoRAs into one generalist. + +```yaml +merge: + enabled: true + algorithm: "ties" + base_model: "Qwen/Qwen2.5-7B-Instruct" + models: + - { path: "./checkpoints/customer-support", weight: 0.4 } + - { path: "./checkpoints/code-assistant", weight: 0.3 } + - { path: "./checkpoints/math-reasoning", weight: 0.3 } + parameters: + threshold: 0.7 + output: + dir: "./checkpoints/merged" + model_card: true + evaluation: + benchmark: + tasks: ["mmlu", "humaneval", "gsm8k"] + floors: { mmlu: 0.50, humaneval: 0.40, gsm8k: 0.50 } +``` + +```shell +$ forgelm --merge --config configs/merge.yaml +``` + +## Air-gap-ready customer support + +Same as the customer-support template but with everything pre-cached and `--offline` enforced. + +```yaml +# configs/customer-support-airgap.yaml +# Pre-requisites: forgelm cache-models / cache-tasks already run + +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" # must be cached + load_in_4bit: true + +# ... (same training config as customer-support template) + +evaluation: + safety: + enabled: true + model: "meta-llama/Llama-Guard-3-8B" # must be cached + judge: + enabled: false # OpenAI judge unavailable offline + trend: + enabled: true # local + +compliance: + audit_log: + forward_to: + - type: "syslog" + host: "audit.internal:514" # internal-only + protocol: "tcp" + +output: + webhook: + url: "https://internal-webhooks.example/forgelm" + allow_private: true # required for internal IPs +``` + +Run: + +```shell +$ HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \ + forgelm --config configs/customer-support-airgap.yaml --offline +``` + +## See also + +- [Configuration Reference](#/reference/configuration) — every field these templates use. +- [CLI Reference](#/reference/cli) — commands these templates expect. +- [Your First Run](#/getting-started/first-run) — the customer-support template walkthrough. diff --git a/docs/usermanuals/en/training/distributed.md b/docs/usermanuals/en/training/distributed.md new file mode 100644 index 00000000..e3f6f67c --- /dev/null +++ b/docs/usermanuals/en/training/distributed.md @@ -0,0 +1,148 @@ +--- +title: Distributed Training +description: Multi-GPU training with DeepSpeed ZeRO, FSDP, and the Unsloth backend. +--- + +# Distributed Training + +Once your model is bigger than a single GPU's memory — or you simply want to train faster — distributed training is the answer. ForgeLM supports DeepSpeed ZeRO-2/3, PyTorch FSDP, and the Unsloth single-GPU acceleration backend. + +## Decision tree + +```mermaid +flowchart TD + Q1{How many GPUs
do you have?} + Q2{Single GPU
OOM?} + Q3{Need multi-node
training?} + Q4{Prefer DeepSpeed
or PyTorch native?} + + Q1 -->|1| Q2 + Q1 -->|2-8| Q4 + Q1 -->|>8 nodes| Q3 + Q2 -->|No| Unsloth([Unsloth + LoRA]) + Q2 -->|Yes| QLoRA([QLoRA]) + Q3 --> ZeRO3([ZeRO-3]) + Q4 -->|DeepSpeed| Z[ZeRO-2 or ZeRO-3] + Q4 -->|PyTorch native| FSDP([FSDP]) + + classDef question fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + classDef result fill:#1c2030,stroke:#22c55e,color:#e6e7ec + class Q1,Q2,Q3,Q4 question + class Unsloth,QLoRA,ZeRO3,Z,FSDP result +``` + +## Backend cheat sheet + +| Backend | Multi-GPU? | Multi-node? | Notes | +|---|---|---|---| +| **Single GPU + Unsloth** | No | No | 2-5× faster than vanilla on Llama/Qwen/Mistral. Always use this first if you're on one GPU. | +| **DeepSpeed ZeRO-2** | Yes | Yes | Shards optimiser state. Good speed, supports any model. | +| **DeepSpeed ZeRO-3** | Yes | Yes | Shards optimiser + grads + params. Required for very large models. | +| **DeepSpeed ZeRO-3 Offload** | Yes | Yes | Offloads to CPU/NVMe. Trades speed for fitting huge models. | +| **FSDP** | Yes | Yes | PyTorch native. Slightly faster than ZeRO-3 on identical configs; less mature ecosystem. | + +## Unsloth (single GPU) + +Unsloth is a drop-in optimisation for Llama, Qwen, Mistral, and a few others. It rewrites the attention and MLP layers in Triton for ~2-5× speedup with no quality loss. + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + use_unsloth: true # the only flag you need + +training: + trainer: "sft" + # ... rest of training config unchanged +``` + +:::tip +Unsloth has model-specific kernels. If your architecture isn't supported, ForgeLM logs a warning and falls back to the standard backend. Supported families are listed in [Configuration Reference](#/reference/configuration). +::: + +## DeepSpeed ZeRO-2 + +ZeRO-2 shards the optimiser state (the heaviest VRAM component for adaptive optimisers like Adam). Effective for 13B-30B models on 4-8 GPUs. + +```yaml +distributed: + strategy: "deepspeed" + zero_stage: 2 + gradient_accumulation_steps: 4 + cpu_offload: false +``` + +Launch: + +```shell +$ accelerate launch --num_processes 4 -m forgelm --config configs/run.yaml +# or +$ deepspeed --num_gpus 4 -m forgelm --config configs/run.yaml +``` + +## DeepSpeed ZeRO-3 + +ZeRO-3 additionally shards gradients and parameters across GPUs. Each GPU holds only `1/N` of the model. Essential for 70B+ models. + +```yaml +distributed: + strategy: "deepspeed" + zero_stage: 3 + gradient_accumulation_steps: 8 + cpu_offload: false # set true to fit 70B on 8x24 GB + nvme_offload_path: null # set for ZeRO-Infinity to NVMe +``` + +| Model | GPUs | ZeRO-3 + offload? | +|---|---|---| +| 30B | 4× A100 40 GB | Optional | +| 70B | 8× A100 40 GB | CPU offload required | +| 70B | 4× A100 80 GB | No offload needed | +| 405B | 8× H100 80 GB | NVMe offload | + +## FSDP (PyTorch native) + +FSDP shards similarly to ZeRO-3 but uses PyTorch's native FullyShardedDataParallel. Marginally faster on identical setups; slightly less ecosystem maturity (e.g. some HF integrations expect DeepSpeed). + +```yaml +distributed: + strategy: "fsdp" + fsdp_state_dict_type: "FULL_STATE_DICT" + fsdp_auto_wrap_policy: "TRANSFORMER_BASED_WRAP" + fsdp_offload_params: false +``` + +## Gradient accumulation + +Whichever backend you use, gradient accumulation lets you target an effective batch size larger than your VRAM allows: + +```yaml +training: + batch_size: 1 # per-device + gradient_accumulation_steps: 32 # effective batch = 1 × 32 × num_gpus +``` + +8 GPUs × 1 batch × 32 accumulation = effective batch size 256, which is what most large training runs target. + +## Common pitfalls + +:::warn +**ZeRO-3 + LoRA loading fails.** ZeRO-3 requires special handling for parameters that aren't trained. Set `lora.modules_to_save` carefully and use `accelerate launch` (not raw `python -m`). +::: + +:::warn +**Mixing DeepSpeed and FSDP configs.** Pick one. The schema rejects setting both `distributed.zero_stage` and `distributed.fsdp_*` at the same time. +::: + +:::warn +**Inconsistent batch sizes across nodes.** All nodes must agree on batch size and accumulation. ForgeLM raises an error early if mismatched, but only if you remember to validate from each node — `--dry-run` from the launching node is sufficient. +::: + +:::tip +For multi-node, configure SSH access between nodes and use `accelerate config` to record the node list. ForgeLM picks up the resulting config automatically. +::: + +## See also + +- [GaLore](#/training/galore) — full-parameter training in less VRAM, alternative to ZeRO-3. +- [VRAM Fit-Check](#/operations/vram-fit-check) — verify before launching a multi-GPU job. +- [CI/CD Pipelines](#/operations/cicd) — multi-GPU training in automated pipelines. diff --git a/docs/usermanuals/en/training/dpo.md b/docs/usermanuals/en/training/dpo.md new file mode 100644 index 00000000..b52578e1 --- /dev/null +++ b/docs/usermanuals/en/training/dpo.md @@ -0,0 +1,228 @@ +--- +title: Direct Preference Optimization (DPO) +description: Align a model on chosen/rejected response pairs without RL or a reward model. +--- + +# Direct Preference Optimization (DPO) + +DPO trains a model directly on pairs of (chosen, rejected) responses, aligning its outputs with human preferences without the complexity of reinforcement learning or training a separate reward model. It's the most common alignment technique after SFT. + +## When to use DPO + +```mermaid +flowchart TD + Q1{Do you have
preference pairs?} + Q2{Do you have
reference model
in memory?} + Q3{Is VRAM
tight?} + Q4{Binary feedback
only?} + SFT[Use SFT] + DPO([Use DPO]) + SIMPO[Use SimPO] + KTO[Use KTO] + QLORA[Use QLoRA + DPO] + + Q1 -->|No, only positives| SFT + Q1 -->|Yes| Q4 + Q4 -->|Yes, single response| KTO + Q4 -->|No, paired| Q2 + Q2 -->|No| SIMPO + Q2 -->|Yes| Q3 + Q3 -->|Yes| QLORA + Q3 -->|No| DPO + + classDef question fill:#1c2030,stroke:#f97316,color:#e6e7ec + classDef recommend fill:#161a24,stroke:#22c55e,color:#e6e7ec + classDef alternative fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + class Q1,Q2,Q3,Q4 question + class DPO,QLORA recommend + class SFT,SIMPO,KTO alternative +``` + +| Use DPO when... | Don't use DPO when... | +|---|---| +| You have a dataset of preference pairs (e.g. agent thumbs-up/down). | You only have positive examples. Use [SFT](#/training/sft). | +| You've already done SFT and want to align outputs further. | You don't have a reference model in memory. Use [SimPO](#/training/simpo). | +| You want a stable, well-studied algorithm with predictable behaviour. | Your VRAM is tight — DPO needs ~2× the memory of SFT. | +| You want closed-form gradient estimates (no sampling required). | You have only binary feedback (yes/no on a single response). Use [KTO](#/training/kto). | + +:::tip +Most production teams use the recipe **SFT → DPO** in sequence: SFT teaches the model the format and content of correct responses, DPO sharpens preferences between competing responses. ORPO combines both stages but has slightly less flexibility. +::: + +## Quick example + +A minimal DPO run on a model that's already been SFT-trained: + +```yaml +model: + name_or_path: "./checkpoints/sft-base" # SFT output, or HF model + max_length: 4096 + +lora: + r: 16 + alpha: 32 + +datasets: + - path: "data/preferences.jsonl" + format: "preference" + +training: + trainer: "dpo" + epochs: 1 + batch_size: 2 + learning_rate: 5.0e-6 # ~10× smaller than SFT + dpo: + beta: 0.1 # KL strength + +output: + dir: "./checkpoints/dpo" +``` + +Run it: + +```shell +$ forgelm --config configs/dpo.yaml --dry-run +$ forgelm --config configs/dpo.yaml --fit-check +$ forgelm --config configs/dpo.yaml +``` + +## Dataset format + +DPO requires the **preference** format: each row contains a `prompt`, a `chosen` response, and a `rejected` response. + +```json +{"prompt": "How do I cancel my subscription?", "chosen": "You can cancel from Settings → Billing → Cancel subscription. Your access continues until the end of the billing period.", "rejected": "Just stop paying lol."} +``` + +| Field | Type | Required | Notes | +|---|---|---|---| +| `prompt` | string | yes | The user's message or system+user pair. | +| `chosen` | string | yes | The preferred completion. | +| `rejected` | string | yes | The dispreferred completion. | +| `system` | string | no | Optional system prompt; merged into the prompt at training time. | + +ForgeLM's data audit (`forgelm audit`) catches preference rows where `chosen` and `rejected` are identical (a common bug in preference collection pipelines). See [Dataset Audit](#/data/audit) for details. + +## Configuration parameters + +The `training.dpo` block holds DPO-specific knobs. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `beta` | float | `0.1` | KL divergence regularisation strength. Lower = closer to reference model, higher = more aggressive preference shift. | +| `loss_type` | string | `"sigmoid"` | One of `sigmoid` (original DPO), `hinge` (RLHF-style margin), `ipo` (IPO regularisation), `kto` (KTO-style binary loss). | +| `label_smoothing` | float | `0.0` | Smoothing on preference labels; helps when annotations are noisy. | +| `reference_free` | bool | `false` | Skip the reference model entirely (closer to SimPO). Saves memory but trains less stably. | +| `reference_model` | string | (auto) | Path to an explicit reference model. Defaults to the model being trained, frozen. | +| `loss_dpop_lambda` | float | `null` | Enable DPO-Positive (DPOP) regularisation. `0.5` is a sensible starting point. | +| `pref_chosen_weight` | float | `1.0` | Up-weight chosen responses during loss computation; useful when chosen responses are rarer. | + +The full set of training-block parameters (epochs, learning rate, scheduler, etc.) applies to DPO too — see [Configuration Reference](#/reference/configuration) for the complete list. + +## Memory and compute + +DPO is memory-hungry because it keeps both the policy model (the one being trained) and a reference model in VRAM at the same time. + +:::warn +**Plan for ~2× the VRAM of an equivalent SFT run.** A 7B model that fits in 12 GB for SFT typically needs 22-24 GB for DPO with the same `max_length`. Workarounds: + +- Use **QLoRA + DPO** — both models load in 4-bit. See [LoRA, QLoRA, DoRA](#/training/lora). +- Reduce `max_length` from 4096 to 2048 if your data allows. +- Switch to **SimPO** if your team can accept reference-free training. See [SimPO](#/training/simpo). +- Enable `reference_free: true` (less stable but skips the second model). +::: + +Run `forgelm --config X.yaml --fit-check` before submitting a long DPO job — it estimates peak VRAM and reports `FITS / TIGHT / OOM / UNKNOWN` with concrete suggestions if your budget is tight. + +## Choosing `beta` + +`beta` is the most important DPO hyperparameter and the one most often gotten wrong. + +| `beta` value | Behaviour | When to use | +|---|---|---| +| `0.01 – 0.05` | Very gentle preference shift; model stays close to reference. | High-quality, narrow preference signal; large preference dataset. | +| `0.1` | Default. Balanced trade-off between preference adherence and reference fidelity. | Most workflows. **Start here.** | +| `0.3 – 0.5` | Aggressive preference shift; model diverges further from reference. | Coarse preferences, small dataset, willing to trade away some general ability. | +| `> 0.5` | Often unstable; reward hacking risk. | Rarely. Increase only if `0.1` and `0.3` aren't shifting outputs noticeably. | + +:::tip +If your training loss decreases but your evaluation metrics regress, you're over-fitting on preferences — *lower* `beta`. If preferences aren't shifting at all, *raise* `beta` or check your dataset for `chosen == rejected` rows. +::: + +## Combining DPO with safety evaluation + +In production, you almost always run DPO with safety evaluation and auto-revert enabled. A DPO run that increases helpfulness while regressing on the Llama Guard safety check is worse than no run at all. + +```mermaid +sequenceDiagram + participant User as You + participant FL as ForgeLM + participant Eval as Eval pipeline + participant Guard as Llama Guard + participant Bench as lm-eval-harness + participant Audit as Audit log + + User->>FL: forgelm --config dpo.yaml + FL->>FL: SFT checkpoint loaded as reference + FL->>FL: DPO training (epoch 1..N) + FL->>Eval: Post-train evaluation + Eval->>Guard: Score across S1-S14 + Guard-->>Eval: Per-category confidence + Eval->>Bench: Run benchmark suite + Bench-->>Eval: Per-task accuracy + alt Any threshold violated + Eval->>FL: Regression detected + FL->>FL: Restore SFT checkpoint + FL->>Audit: Append incident record + FL-->>User: Exit 3 + structured report + else All thresholds pass + FL->>Audit: Append success record + FL-->>User: Exit 0 + DPO checkpoint + end +``` + +```yaml +training: + trainer: "dpo" + dpo: { beta: 0.1 } + +evaluation: + safety: + enabled: true + model: "meta-llama/Llama-Guard-3-8B" + block_categories: ["S1", "S2", "S5", "S10"] # the categories you must not regress on + benchmark: + tasks: ["truthfulqa", "hellaswag"] + floors: { truthfulqa: 0.45 } # auto-revert if it drops below + +compliance: + human_approval: true # Article 14 oversight gate +``` + +If post-train Llama Guard scores show a regression in any blocked category, ForgeLM automatically rolls back to the pre-DPO checkpoint and emits a structured incident record. See [Auto-Revert](#/evaluation/auto-revert) for the gating logic. + +## Common pitfalls + +:::warn +**Identical `chosen` and `rejected` rows.** Symptom: DPO loss converges immediately near zero. Fix: run `forgelm audit` on your preference dataset; it flags `chosen == rejected` collisions and near-duplicates. +::: + +:::warn +**Learning rate too high.** DPO is sensitive to learning rate. Start at `5e-6` for full fine-tunes or `1e-5` for LoRA-on-DPO. SFT learning rates (1e-4 to 5e-4) cause divergence. +::: + +:::warn +**Reference model drift.** If you train SFT and DPO with different LoRA adapters, the reference model used for DPO may not match what you think it is. Save the SFT checkpoint and explicitly set `model.name_or_path` to its directory for DPO. +::: + +:::danger +**Mixing SFT and DPO in a single dataset.** Don't put SFT-format rows (`{prompt, completion}`) into the same JSONL as DPO-format rows (`{prompt, chosen, rejected}`). The data loader can't unambiguously route them. Use separate files and reference both via `datasets:` if you genuinely need to mix. +::: + +## See also + +- [SFT](#/training/sft) — supervised fine-tuning, the usual prerequisite for DPO. +- [SimPO](#/training/simpo) — reference-free preference learning, lower VRAM. +- [ORPO](#/training/orpo) — combines SFT and DPO into one stage. +- [Auto-Revert](#/evaluation/auto-revert) — the safety net for preference training. +- [Configuration Reference](#/reference/configuration) — full list of training parameters. diff --git a/docs/usermanuals/en/training/galore.md b/docs/usermanuals/en/training/galore.md new file mode 100644 index 00000000..446f579b --- /dev/null +++ b/docs/usermanuals/en/training/galore.md @@ -0,0 +1,92 @@ +--- +title: GaLore +description: Full-parameter training in LoRA-level memory via gradient low-rank projection. +--- + +# GaLore + +GaLore (**G**radient **L**ow-**R**ank Projection) trains *all* parameters of a model — but at LoRA-level memory cost. Instead of storing the full optimiser state, GaLore projects gradients to a low-rank subspace, periodically re-projecting as training proceeds. + +The result: full fine-tune quality at ~LoRA memory. + +## When to use GaLore + +| Use GaLore when... | Use LoRA/QLoRA when... | +|---|---| +| You want full-parameter training but VRAM is tight. | A small adapter is all you need. | +| LoRA underfits — quality plateaus before convergence. | LoRA at rank 32-64 already meets your bar. | +| You have time for slightly slower training (~15-20% slower per step). | Wall-clock speed matters more than raw quality. | +| You're fine-tuning math or reasoning models where every weight matters. | You're doing instruction tuning. | + +## Quick example + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: false # GaLore prefers full precision + max_length: 4096 + +galore: + enabled: true + rank: 256 # higher than LoRA — projection rank + update_proj_gap: 200 # re-project every N steps + scale: 0.25 + proj_type: "std" # std (default), reverse_std, right, left + +training: + trainer: "sft" + learning_rate: 1.0e-5 # full-FT learning rate, not LoRA + optimizer: "galore_adamw_8bit" + +output: + dir: "./checkpoints/galore" +``` + +Note: when `galore.enabled: true`, ForgeLM automatically uses the GaLore-aware optimiser; `lora` should not be configured at the same time. + +## Configuration parameters + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `enabled` | bool | `false` | Master switch. | +| `rank` | int | `256` | Gradient projection rank. Higher = closer to full-FT, more memory. | +| `update_proj_gap` | int | `200` | Steps between re-projections. Lower = adapt to changing gradients faster. | +| `scale` | float | `0.25` | Scaling on the projected gradients. | +| `proj_type` | string | `"std"` | Projection direction. `std` is the default; experiment if convergence stalls. | +| `target_modules` | list | `["attn", "mlp"]` | Which modules to project gradients for. | + +## Memory comparison + +For a 7B model at `max_length: 4096`, batch size 1: + +| Method | Trainable params | VRAM (full precision) | VRAM (4-bit base) | +|---|---|---|---| +| Full FT | 100% | 56 GB | n/a | +| LoRA r=16 | 0.2% | 18 GB | 9 GB (QLoRA) | +| **GaLore r=256** | **100%** | **22 GB** | n/a | + +So GaLore at r=256 lets you full-fine-tune a 7B model on a single 24 GB GPU — roughly the same VRAM as plain LoRA at full precision. + +## Compute + +GaLore is ~15-20% slower per step than LoRA because of the projection/re-projection overhead. End-to-end the difference often disappears: GaLore frequently converges in fewer steps because it has access to the full parameter space. + +## Common pitfalls + +:::warn +**Trying to combine GaLore with LoRA.** They're alternatives, not complements. ForgeLM's config schema rejects setting both `lora.r` and `galore.enabled`. +::: + +:::warn +**Using LoRA learning rates.** GaLore is full-parameter — use full-FT learning rates (1e-5 to 5e-5), not LoRA learning rates (1e-4 to 5e-4). +::: + +:::warn +**Setting `update_proj_gap` too high.** Re-projecting infrequently means the gradient subspace doesn't track the optimisation trajectory well. Default 200 is reasonable; don't go above 500. +::: + +## See also + +- [LoRA, QLoRA, DoRA](#/training/lora) — the more common alternative. +- [Distributed Training](#/training/distributed) — for models bigger than a single GPU. +- [Configuration Reference](#/reference/configuration) — full GaLore parameter list. diff --git a/docs/usermanuals/en/training/grpo.md b/docs/usermanuals/en/training/grpo.md new file mode 100644 index 00000000..bac70dc8 --- /dev/null +++ b/docs/usermanuals/en/training/grpo.md @@ -0,0 +1,139 @@ +--- +title: Group Relative Policy Optimization (GRPO) +description: Reinforcement learning for reasoning — train against a reward function with built-in shaping. +--- + +# Group Relative Policy Optimization (GRPO) + +GRPO is the reinforcement-learning trainer in ForgeLM. The model generates several responses to each prompt, your reward function scores them, and GRPO updates the policy to favour higher-reward outputs. It's the right choice for tasks with verifiable correctness (math, code) or programmatic quality signals. + +## When to use GRPO + +| Use GRPO when... | Use DPO/SimPO when... | +|---|---| +| You can write a reward function (math grader, test runner). | Your quality signal is human preferences only. | +| Tasks have a verifiable correct answer. | Tasks are open-ended ("write a marketing email"). | +| You want format-shaping rewards in addition to correctness. | You need stable, well-understood training dynamics. | +| You're building a reasoning model. | You're building a chat assistant. | + +```mermaid +flowchart LR + A[Prompt] --> B[Sample N responses] + B --> C[Score each
with reward fn] + C --> D[Compute group-relative
advantage] + D --> E[Update policy] + E --> A + classDef step fill:#1c2030,stroke:#f97316,color:#e6e7ec + classDef io fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + class A,E io + class B,C,D step +``` + +## Quick example + +```yaml +model: + name_or_path: "./checkpoints/sft-base" + max_length: 4096 + +datasets: + - path: "data/math-prompts.jsonl" + format: "reward" + +training: + trainer: "grpo" + epochs: 1 + batch_size: 1 + learning_rate: 1.0e-6 + grpo: + group_size: 8 # samples per prompt + beta: 0.04 # KL strength + reward_function: "my_reward.score" + format_reward: 0.2 # weight of built-in format shaping + +output: + dir: "./checkpoints/grpo" +``` + +```python +# my_reward.py +def score(prompt: str, response: str, ground_truth: str) -> float: + """Return a scalar; positive for correct, negative for incorrect.""" + answer = parse_number(response) + if answer is None: + return -0.5 + return 1.0 if abs(answer - float(ground_truth)) < 1e-6 else -1.0 +``` + +## Built-in format shaping + +ForgeLM ships with a default reward shaper that rewards: + +- **Format adherence** — output ends with a clear answer in the expected format (e.g. `\boxed{...}` for math). +- **Length compliance** — outputs neither too short nor rambling. +- **Reasoning structure** — chain-of-thought before the final answer. + +The shaper composes with your custom reward: + +```yaml +training: + grpo: + reward_function: "my_reward.score" # 80% weight + format_reward: 0.2 # 20% weight on the shaper + answer_pattern: '\\boxed\\{(.*?)\\}' # regex for the "final answer" +``` + +## Configuration parameters + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `group_size` | int | `8` | Responses sampled per prompt. Higher = more stable advantage estimates, more compute. | +| `beta` | float | `0.04` | KL regularisation. GRPO's beta is much smaller than DPO's because the gradient signal is amplified. | +| `reward_function` | string | `null` | Dotted path to your reward function. | +| `format_reward` | float | `0.0` | Weight of the built-in format shaper. `0.2` is sensible. | +| `answer_pattern` | string | `null` | Regex for extracting the "final answer". Used by the format shaper. | +| `temperature` | float | `0.9` | Sampling temperature. Higher = more diverse responses. | +| `max_completion_length` | int | `2048` | Cap on generated response length. | + +## Compute and memory + +GRPO is the heaviest trainer: + +- Generates `group_size` responses per prompt (default 8) — that's 8× the inference cost of DPO. +- Keeps a reference model in memory. +- Reward computation may load additional models (judge LLM, reward model). + +| Model | LoRA | `group_size` | Approx VRAM (QLoRA) | +|---|---|---|---| +| 7B | yes | 8 | 18 GB | +| 13B | yes | 8 | 28 GB (needs 40 GB) | +| 7B | no | 8 | needs ZeRO-3 | + +## Common pitfalls + +:::warn +**Reward function with wrong scale.** Rewards in `[0, 1]` (or `[-1, 1]`) work best. Unbounded rewards (e.g. `correct ? 1000 : 0`) cause gradient explosions. Normalise to a sensible bounded range. +::: + +:::warn +**`group_size` too small.** With `group_size=2`, GRPO's group-relative advantage estimate has no statistical power. Use 4 minimum, 8+ for stability. +::: + +:::warn +**No SFT first.** GRPO from a base model rarely produces useful results — the model can't even output the right format, so almost every sample gets the minimum reward. SFT for format first, GRPO for correctness second. +::: + +:::danger +**Reward hacking.** The model will exploit any unintended pattern in your reward function. Common cases: +- Rewarding chain-of-thought length → model writes infinitely. +- Rewarding the exact-string match of a final answer → model outputs nothing else. +- Rewarding "no errors in syntax" → model outputs trivial code that doesn't solve the problem. + +Test your reward function against adversarial outputs *before* training. The format shaper helps but isn't a complete defence. +::: + +## See also + +- [Choosing a Trainer](#/concepts/choosing-trainer) — when GRPO beats DPO. +- [Auto-Revert](#/evaluation/auto-revert) — catch reward-hacking regressions. +- [Configuration Reference](#/reference/configuration) — full parameter list. diff --git a/docs/usermanuals/en/training/kto.md b/docs/usermanuals/en/training/kto.md new file mode 100644 index 00000000..f07f2d66 --- /dev/null +++ b/docs/usermanuals/en/training/kto.md @@ -0,0 +1,91 @@ +--- +title: Kahneman-Tversky Optimization (KTO) +description: Preference alignment from binary thumbs-up/down feedback, not paired comparisons. +--- + +# Kahneman-Tversky Optimization (KTO) + +KTO trains a model on binary feedback — thumbs-up or thumbs-down on a single response — rather than paired chosen/rejected comparisons. Use it when your feedback collection produces single-response judgements, which is far more common in production than rigorous A/B preference data. + +## When to use KTO + +| Use KTO when... | Use DPO/SimPO when... | +|---|---| +| You have user thumbs-up/down on individual responses. | You have side-by-side `(chosen, rejected)` pairs. | +| Your annotation budget can't afford paired comparisons. | Your annotators rate pairs side-by-side. | +| Your feedback comes from production telemetry. | Feedback comes from labelling sessions. | + +KTO's loss is built on prospect theory — the same psychology behind Kahneman-Tversky's original work. The model learns to maximise utility for desirable responses and minimise utility for undesirable ones, without ever seeing them paired. + +## Quick example + +```yaml +model: + name_or_path: "./checkpoints/sft-base" + max_length: 4096 + +datasets: + - path: "data/feedback.jsonl" + format: "binary" + +training: + trainer: "kto" + epochs: 1 + learning_rate: 5.0e-7 + kto: + beta: 0.1 + desirable_weight: 1.0 + undesirable_weight: 1.0 + +output: + dir: "./checkpoints/kto" +``` + +## Dataset format + +```json +{"prompt": "How do I cancel?", "response": "Just stop paying lol.", "label": false} +{"prompt": "How do I cancel?", "response": "From Settings → Billing…", "label": true} +``` + +KTO needs both classes — at minimum 5-10% of your data should be the minority class. If your dataset is 99% thumbs-up and 1% thumbs-down (which is typical of production telemetry), KTO will struggle to find a useful signal in the rare class. + +## Configuration parameters + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `beta` | float | `0.1` | KL strength, same role as DPO. | +| `desirable_weight` | float | `1.0` | Up-weight thumbs-up rows in the loss. | +| `undesirable_weight` | float | `1.0` | Up-weight thumbs-down rows. | +| `loss_type` | string | `"sigmoid"` | `sigmoid` or `kto-pair` (paired-loss variant). | + +:::tip +**Imbalanced data?** Set `undesirable_weight: 5.0` (or whatever ratio matches your imbalance) to amplify the rare-class signal. Don't oversample the JSONL itself — let the loss weights do it. +::: + +## Compute and memory + +About 1.5× SFT memory — keeps a reference model like DPO does, but processes single rows instead of paired ones. + +## When KTO surprises people + +KTO often *outperforms* DPO when applied to real-world thumbs-up/down telemetry, even when the same data could have been re-shaped into pairs. Two reasons: + +1. Forced pairing creates spurious comparisons — a thumbs-up on one prompt and a thumbs-down on a different prompt aren't really "preferred vs dispreferred" of the same thing. +2. Production telemetry is imbalanced; KTO's per-class weights handle that more naturally. + +## Common pitfalls + +:::warn +**Treating `label: 1/0` as `true/false`.** Use the JSON booleans `true` and `false`, not integers. The data loader rejects integer labels for KTO. +::: + +:::warn +**Single-class data.** If 100% of your rows are `label: true`, KTO has nothing to push against. The training will run but produce a near-identical model. +::: + +## See also + +- [DPO](#/training/dpo) — paired-preference cousin. +- [Dataset Formats](#/concepts/data-formats) — the `binary` format. +- [Choosing a Trainer](#/concepts/choosing-trainer) — decision tree. diff --git a/docs/usermanuals/en/training/long-context.md b/docs/usermanuals/en/training/long-context.md new file mode 100644 index 00000000..244ea1c6 --- /dev/null +++ b/docs/usermanuals/en/training/long-context.md @@ -0,0 +1,140 @@ +--- +title: Long-Context Training +description: Train on 32K-128K context windows with RoPE scaling, NEFTune, sliding-window attention, and sample packing. +--- + +# Long-Context Training + +Modern base models often ship with 8K-32K native context, but real-world tasks frequently need more — full books, multi-document RAG, long conversations. ForgeLM supports training (and continued pre-training) on extended contexts up to 128K tokens. + +## Techniques in play + +```mermaid +flowchart LR + A[Base 8K context] --> B[RoPE scaling] + B --> C[Sliding window
attention] + C --> D[Sample packing] + D --> E[NEFTune
regularisation] + E --> F[128K-context
fine-tuned model] + classDef step fill:#1c2030,stroke:#f97316,color:#e6e7ec + classDef io fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + class A,F io + class B,C,D,E step +``` + +| Technique | What it does | +|---|---| +| **RoPE scaling** | Re-scales positional embeddings so the model accepts beyond-trained-length inputs. | +| **Sliding-window attention** | Processes long sequences in overlapping windows for memory efficiency. | +| **Sample packing** | Bin-packs short sequences together so each training step fills the context. | +| **NEFTune** | Adds embedding noise during training; small but consistent gains on long-context tasks. | + +## Quick example + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + max_length: 32768 + rope_scaling: + type: "linear" + factor: 4.0 # 8K base × 4 = 32K + sliding_window: 4096 # process in 4K windows + load_in_4bit: true + +training: + trainer: "sft" + packing: true # critical for throughput + neftune_noise_alpha: 5.0 # add training-time embedding noise + +datasets: + - path: "data/long-docs.jsonl" + format: "messages" +``` + +## RoPE scaling types + +| Type | Best for | Notes | +|---|---|---| +| `linear` | Conservative extension (2-4×) | Simple, well-understood, slight quality loss at extreme factors. | +| `dynamic` | Aggressive extension (4-8×) | Adjusts scaling based on input length at inference. | +| `yarn` | Maximum extension (8-32×) | Yarn (Yet another RoPE extensioN) — best quality at extreme contexts. Recommended for >32K. | +| `longrope` | Per-dim scaling | Learns separate scaling per RoPE dimension. Most flexible, most VRAM. | + +For most projects pushing 8K → 32K, `linear` with `factor: 4.0` works. For 8K → 128K, use `yarn`. + +## Memory budget + +Long-context training is VRAM-hungry — attention is `O(N²)` in sequence length. + +| Context | 7B model VRAM (QLoRA, packing on) | Notes | +|---|---|---| +| 4K | 8 GB | Standard. | +| 8K | 11 GB | | +| 16K | 16 GB | Sliding window required for some models. | +| 32K | 24 GB | Sliding window strongly recommended. | +| 64K | 40 GB+ | Multi-GPU territory; ZeRO-3 helps. | +| 128K | 80 GB+ | Very few setups support this without aggressive offloading. | + +Use `forgelm --fit-check` to confirm before submitting a long-context job. See [VRAM Fit-Check](#/operations/vram-fit-check). + +## Sample packing + +Packing combines several short examples into one fixed-length sequence at training time: + +```text +Without packing: [example1] padding padding padding padding padding + [example2] padding padding padding padding padding + +With packing: [example1][example2][example3][example4][example5] +``` + +Throughput improves 30-50% on instruction-tuning data where most examples are far shorter than `max_length`. Quality is unchanged for SFT; ForgeLM masks loss across example boundaries automatically. + +```yaml +training: + packing: true + packing_max_length: 32768 # usually = max_length +``` + +:::warn +Packing assumes examples are independent. If you're training on long documents that should preserve full context (book chapters, source code repos), set `packing: false`. +::: + +## NEFTune + +Adds Gaussian noise to embeddings during training. Despite the simplicity, it consistently improves long-context generalisation: + +```yaml +training: + neftune_noise_alpha: 5.0 # alpha=5 is the typical sweet spot +``` + +Higher `alpha` = more regularisation. Above 10 the model starts producing noise itself. + +## Common pitfalls + +:::warn +**RoPE scaling without retraining.** Setting `rope_scaling.factor: 4.0` and *not* training extends nominal context but the model produces gibberish past native length. You must SFT (even briefly) on long-context data after enabling RoPE scaling. +::: + +:::warn +**Forgetting to extend the tokeniser's context.** Some tokenisers cap at the original context length. Verify with `tokenizer.model_max_length` after configuring RoPE. +::: + +:::warn +**OOM at evaluation, not training.** Eval often runs without sliding window or packing — it can OOM even when training fits. Set evaluation `max_length` lower if needed: +```yaml +evaluation: + max_length: 4096 # eval at native context, train at 32K +``` +::: + +## Continued pre-training + +For aggressive context extension (8K → 128K), a dedicated pre-training pass on long documents helps. ForgeLM doesn't ship a pre-training trainer (that's outside scope) but the trained checkpoint can then be SFT-tuned at the extended context for instruction-following. + +## See also + +- [Configuration Reference](#/reference/configuration) — every long-context flag. +- [Distributed Training](#/training/distributed) — when long context outgrows a single GPU. +- [VRAM Fit-Check](#/operations/vram-fit-check) — check before submitting. diff --git a/docs/usermanuals/en/training/lora.md b/docs/usermanuals/en/training/lora.md new file mode 100644 index 00000000..5221afb8 --- /dev/null +++ b/docs/usermanuals/en/training/lora.md @@ -0,0 +1,146 @@ +--- +title: LoRA, QLoRA, DoRA +description: Parameter-efficient fine-tuning — train ~1% of the weights, get ~95% of the quality, fit on commodity GPUs. +--- + +# LoRA, QLoRA, DoRA + +Low-Rank Adaptation (LoRA) and its variants let you fine-tune large models on small GPUs. Instead of updating every weight, you train low-rank "adapter" matrices alongside the frozen base model — typically ~1% of the parameters, ~10% of the VRAM, and ~90-95% of the quality of full fine-tuning. + +ForgeLM applies LoRA / QLoRA / DoRA to *every* trainer (SFT, DPO, SimPO, KTO, ORPO, GRPO) — it's a property of the optimiser, not the algorithm. + +## When to use each variant + +```mermaid +flowchart TD + Q1{Need to fit on a
consumer GPU
(<24 GB)?} + Q2{Want full-precision
weights kept frozen?} + Q3{Need maximum
quality at LoRA cost?} + Full[Full fine-tuning] + LoRA([LoRA]) + QLoRA([QLoRA]) + DoRA([DoRA]) + + Q1 -->|No, plenty of VRAM| Q2 + Q2 -->|Yes| LoRA + Q2 -->|No, can melt the base| Full + Q1 -->|Yes| Q3 + Q3 -->|Yes| DoRA + Q3 -->|No, default| QLoRA + + classDef question fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + classDef result fill:#1c2030,stroke:#22c55e,color:#e6e7ec + classDef alt fill:#1c2030,stroke:#9ea3b3,color:#e6e7ec + class Q1,Q2,Q3 question + class LoRA,QLoRA,DoRA result + class Full alt +``` + +## Quick reference + +| Variant | What changes | VRAM (relative to full) | When to use | +|---|---|---|---| +| **LoRA** | Adds low-rank matrices alongside attention/MLP weights | 30-40% | Default for full-precision base models. | +| **QLoRA** | LoRA + 4-bit NF4 quantisation of the base model | 10-15% | Default for consumer GPUs. | +| **DoRA** | LoRA decomposed into magnitude × direction | 35-45% | Highest quality at LoRA cost; ~5-10% slower. | +| **PiSSA** | LoRA initialised from the principal singular components | 30-40% | Faster convergence than LoRA on small datasets. | +| **rsLoRA** | LoRA with rank-stabilised scaling | 30-40% | More stable at high ranks (r ≥ 64). | + +## Quick example + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true # enables QLoRA + bnb_4bit_quant_type: "nf4" # default; alternative is "fp4" + bnb_4bit_compute_dtype: "bfloat16" + +lora: + r: 16 # rank — 8/16/32 typical + alpha: 32 # scaling — usually 2× rank + dropout: 0.05 + use_dora: false # set true for DoRA + target_modules: ["q_proj", "k_proj", "v_proj", "o_proj"] + modules_to_save: [] # extra modules trained at full precision + +training: + trainer: "sft" + learning_rate: 2.0e-4 # LoRA tolerates higher LR than full FT +``` + +## Choosing rank `r` + +Rank is the single most important hyperparameter for LoRA quality. + +| Rank | Trainable params (7B model) | When to use | +|---|---|---| +| 4 | 0.05% | Style transfer, format-only training. Cheap. | +| 8 | 0.1% | Domain adaptation; small dataset (<5K rows). | +| 16 | 0.2% | **Default.** Most use cases. | +| 32 | 0.4% | Larger datasets (50K+); harder tasks. | +| 64 | 0.8% | Approaching full fine-tune quality. | +| 128 | 1.5% | Diminishing returns; usually full FT is better. | + +`alpha` typically scales with rank — a common rule is `alpha = 2 × r`. + +## Target modules + +LoRA only trains the modules you point it at. Defaults are reasonable for most architectures, but you can broaden or narrow the scope: + +```yaml +lora: + target_modules: "all-linear" # broadest — every Linear layer + # or specifically: + target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"] + # or just attention: + target_modules: ["q_proj", "v_proj"] +``` + +Broader = more capacity but more VRAM. The default (Q/K/V/O projections) is the right balance for most tasks. + +## DoRA — when it pays off + +DoRA decomposes each weight into a magnitude vector and a direction matrix, training both with low rank. Empirical results: DoRA narrows the gap between LoRA and full fine-tuning, often matching full FT quality. + +```yaml +lora: + r: 16 + alpha: 32 + use_dora: true +``` + +Trade-off: ~5-10% slower training and ~10% more VRAM than plain LoRA. Use DoRA when: +- You'd otherwise need to step up to full fine-tuning. +- You're seeing LoRA underfit on a hard task. + +## Common pitfalls + +:::warn +**Setting `r` too high.** Rank 128 LoRA is roughly equivalent in compute and quality to a partial full fine-tune — and usually worse than picking a smaller model and doing full FT. If `r > 64` keeps coming up, reconsider the approach. +::: + +:::warn +**Forgetting `modules_to_save` for embedding changes.** If you add new tokens to the tokeniser, the embedding and lm_head need full-precision training: +```yaml +lora: + modules_to_save: ["embed_tokens", "lm_head"] +``` +::: + +:::warn +**Loading the wrong base for inference.** When you train QLoRA, the adapter is saved in full precision but the base remains 4-bit. At inference, you must either: +- Re-load the base in 4-bit and apply the adapter, or +- Merge the adapter into a full-precision base for serving. + +ForgeLM's `forgelm export` does this correctly; if you're loading manually, watch for type mismatches. +::: + +:::tip +**Save adapter only.** Default behaviour: ForgeLM saves only the adapter weights (~50-200 MB) plus a model card pointing at the base. To merge for deployment, run `forgelm export ./checkpoints/run --merge`. +::: + +## See also + +- [GaLore](#/training/galore) — full-parameter training in LoRA-level memory. +- [Configuration Reference](#/reference/configuration) — every LoRA/quantisation field. +- [Model Merging](#/deployment/model-merging) — combining multiple adapters. diff --git a/docs/usermanuals/en/training/orpo.md b/docs/usermanuals/en/training/orpo.md new file mode 100644 index 00000000..e4d02983 --- /dev/null +++ b/docs/usermanuals/en/training/orpo.md @@ -0,0 +1,86 @@ +--- +title: Odds Ratio Preference Optimization (ORPO) +description: Combine SFT and preference learning into a single training stage. +--- + +# Odds Ratio Preference Optimization (ORPO) + +ORPO collapses SFT and DPO into one training pass. The loss combines a standard SFT term (on `chosen`) with an odds-ratio penalty against `rejected`. The result: faster wall-clock, no separate stages, no reference model. + +## When to use ORPO + +| Use ORPO when... | Use SFT → DPO when... | +|---|---| +| You want one training stage instead of two. | You want to inspect SFT before deciding on alignment. | +| Wall-clock time matters (e.g. CI/CD overnight runs). | You'll iterate on preference data more than SFT data. | +| You have both pairs and clean SFT data ready. | You only have SFT data now and preferences later. | +| You're starting from a base model. | You're aligning an already-SFT-trained model. | + +:::tip +ORPO is the only alignment method that works well *directly* from a base model without an SFT prerequisite — because it includes its own SFT term. +::: + +## Quick example + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true + max_length: 4096 + +datasets: + - path: "data/preferences.jsonl" + format: "preference" + +training: + trainer: "orpo" + epochs: 1 + batch_size: 2 + learning_rate: 5.0e-6 + orpo: + beta: 0.1 # weight of the odds-ratio penalty + +output: + dir: "./checkpoints/orpo" +``` + +## Dataset format + +`preference` format with `prompt`, `chosen`, `rejected`. ORPO's SFT term trains on `chosen`; the odds-ratio term penalises `rejected`. See [Dataset Formats](#/concepts/data-formats). + +## Configuration parameters + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `beta` | float | `0.1` | Strength of the odds-ratio penalty term. Higher = more preference shift. | +| `loss_type` | string | `"sigmoid"` | Currently only `sigmoid` is supported. | +| `sft_weight` | float | `1.0` | Weight of the SFT term in the combined loss. Lower for emphasis on preferences. | + +## Compute and memory + +About 1.5× SFT memory — no reference model required (unlike DPO), but the loss processes both `chosen` and `rejected` per row. + +## When ORPO struggles + +| Situation | Why | +|---|---| +| Very small preference dataset (<2K rows) | Combined loss needs more data than separate SFT+DPO | +| Quality varies wildly across preference pairs | The combined gradient gets noisy | +| You need to inspect SFT outputs before alignment | ORPO doesn't produce an intermediate SFT checkpoint | + +In those cases, run SFT and DPO as separate stages. + +## Common pitfalls + +:::warn +**Using ORPO on a model that's already SFT-trained.** ORPO's SFT term will continue training the model on the `chosen` responses — fine if you want that, but if you wanted "DPO-only on top of my SFT checkpoint", use [DPO](#/training/dpo) instead. +::: + +:::warn +**Setting `beta` too high.** ORPO's `beta` controls how much the odds-ratio term dominates. Too high and the SFT term gets drowned out — leading to malformed outputs that "win the comparison" but aren't useful. +::: + +## See also + +- [SFT](#/training/sft) and [DPO](#/training/dpo) — the two-stage approach ORPO compresses. +- [Configuration Reference](#/reference/configuration) — full parameter list. diff --git a/docs/usermanuals/en/training/sft.md b/docs/usermanuals/en/training/sft.md new file mode 100644 index 00000000..770eba20 --- /dev/null +++ b/docs/usermanuals/en/training/sft.md @@ -0,0 +1,141 @@ +--- +title: Supervised Fine-Tuning (SFT) +description: The foundation of every alignment pipeline — train a base model on instruction pairs. +--- + +# Supervised Fine-Tuning (SFT) + +SFT is the workhorse of post-training. You give the model examples of correct outputs and it learns the pattern. Almost every project starts here, even if it ends in DPO or GRPO. + +## When to use SFT + +| Use SFT when... | Don't use SFT when... | +|---|---| +| You have prompt-completion pairs (the most common shape). | You only have preference pairs. Use [DPO](#/training/dpo) directly (but see warning below). | +| You're starting from a base model and need to teach format. | You already SFT-trained and only need preference alignment. | +| You want simple, stable, well-understood training dynamics. | You need RL-style reward optimisation. Use [GRPO](#/training/grpo). | + +:::tip +SFT first, almost always. Even teams with rich preference data SFT before DPO/SimPO/KTO — going straight to preference learning on a base model produces unstable, format-broken outputs. +::: + +## Quick example + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true + max_length: 4096 + +lora: + r: 16 + alpha: 32 + +datasets: + - path: "data/train.jsonl" + format: "messages" + +training: + trainer: "sft" + epochs: 3 + batch_size: 4 + learning_rate: 2.0e-4 + warmup_ratio: 0.03 + scheduler: "cosine" + +output: + dir: "./checkpoints/sft" +``` + +```shell +$ forgelm --config configs/sft.yaml --dry-run +$ forgelm --config configs/sft.yaml +``` + +## Dataset format + +Two formats supported. See [Dataset Formats](#/concepts/data-formats) for full detail. + +**Single-turn `instructions`:** +```json +{"prompt": "Translate to French: 'Good morning'.", "completion": "Bonjour."} +``` + +**Multi-turn `messages`:** +```json +{"messages": [ + {"role": "user", "content": "..."}, + {"role": "assistant", "content": "..."} +]} +``` + +## Configuration parameters + +The SFT-specific knobs live alongside the standard `training` block. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `learning_rate` | float | `2e-4` | LoRA: 1e-4 to 5e-4. Full-parameter: 1e-5 to 5e-5. | +| `epochs` | int | `3` | More epochs = more memorisation, less generalisation. | +| `batch_size` | int | `4` | Per-device. Multiply by gradient accumulation steps for effective batch. | +| `max_length` | int | `4096` | Context window during training. Longer = more VRAM. | +| `packing` | bool | `false` | Pack short sequences together for throughput. Adds 30-50% speed. | +| `neftune_noise_alpha` | float | `null` | Embedding-noise regularisation. `5.0` improves on small datasets. | +| `loss_on_completions_only` | bool | `true` | Only compute loss on assistant tokens, not the prompt. Recommended. | + +The full parameter list is in [Configuration Reference](#/reference/configuration). + +## Compute and memory + +SFT is the lightest of all post-training paradigms in memory: + +| Model | LoRA rank | `max_length` | Approx VRAM (QLoRA 4-bit) | +|---|---|---|---| +| 7B | 16 | 4096 | 8 GB | +| 13B | 16 | 4096 | 14 GB | +| 8B Llama 3 | 32 | 8192 | 16 GB | +| 70B | 16 | 2048 | needs 2× A100 + ZeRO | + +Always run `--fit-check` before submitting: + +```shell +$ forgelm --config configs/sft.yaml --fit-check +FITS est. peak 7.8 GB / 12 GB available +``` + +## Common pitfalls + +:::warn +**Learning rate too high for full fine-tunes.** 2e-4 works for LoRA but melts a full-parameter run. For full fine-tuning, drop to 1e-5 to 5e-5. +::: + +:::warn +**Loss going up instead of down.** Likely a tokeniser mismatch — your data was formatted for a different chat template than the one in the model's tokeniser. Re-run `forgelm audit` and check the rendered samples in the audit report. +::: + +:::warn +**Forgetting to enable `loss_on_completions_only`.** With it disabled, the model wastes capacity learning to repeat the prompt. Default is `true`; only disable for unusual training-objective experiments. +::: + +:::tip +**Sample packing speeds things up dramatically.** If your average sample is much shorter than `max_length`, set `packing: true` — ForgeLM bin-packs short examples into single sequences for 30-50% throughput improvement. No quality difference for instruction tuning. +::: + +## What you get on disk + +After training: + +```text +checkpoints/sft/ +├── adapter_model.safetensors ← LoRA weights (or merged checkpoint if not using LoRA) +├── README.md ← model card +├── config_snapshot.yaml ← exact config used +└── artifacts/ ← compliance evidence (if compliance.annex_iv enabled) +``` + +## See also + +- [DPO](#/training/dpo) — the usual next step after SFT. +- [LoRA, QLoRA, DoRA](#/training/lora) — parameter-efficient SFT. +- [Dataset Audit](#/data/audit) — always run before SFT. +- [Configuration Reference](#/reference/configuration) — all training parameters. diff --git a/docs/usermanuals/en/training/simpo.md b/docs/usermanuals/en/training/simpo.md new file mode 100644 index 00000000..a298ebb0 --- /dev/null +++ b/docs/usermanuals/en/training/simpo.md @@ -0,0 +1,96 @@ +--- +title: Simple Preference Optimization (SimPO) +description: Reference-free preference learning — DPO without keeping a reference model in memory. +--- + +# Simple Preference Optimization (SimPO) + +SimPO is a streamlined cousin of DPO that removes the reference model from the equation. The trade-off: roughly half the VRAM, slightly less stability. + +## When to use SimPO + +| Use SimPO when... | Use DPO instead when... | +|---|---| +| Your VRAM budget is tight (e.g. 13B+ on a single 24 GB GPU). | You can afford the second model in memory. | +| You don't have a clean reference checkpoint. | Your SFT checkpoint is high quality and trustworthy. | +| You want simpler training dynamics. | Stability and reproducibility matter more than VRAM. | + +:::tip +A practical rule: if [`--fit-check`](#/operations/vram-fit-check) reports `OOM` for DPO, switch to SimPO before considering smaller models or shorter contexts. The quality gap is usually less than 5% on standard benchmarks. +::: + +## Quick example + +```yaml +model: + name_or_path: "./checkpoints/sft-base" + max_length: 4096 + +datasets: + - path: "data/preferences.jsonl" + format: "preference" + +training: + trainer: "simpo" + epochs: 1 + learning_rate: 8.0e-7 # ~10× smaller than DPO + simpo: + beta: 2.0 # higher than DPO's 0.1 + gamma: 1.0 # margin term + loss_type: "sigmoid" + +output: + dir: "./checkpoints/simpo" +``` + +## Dataset format + +Same as DPO — `preference` format with `prompt`, `chosen`, `rejected`. See [Dataset Formats](#/concepts/data-formats). + +## Configuration parameters + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `beta` | float | `2.0` | Length-normalised reward scale. Higher = stronger preference shift. SimPO's beta is *not* the same scale as DPO's. | +| `gamma` | float | `1.0` | Margin term — the gap SimPO tries to maintain between chosen and rejected log-likelihoods. | +| `loss_type` | string | `"sigmoid"` | `sigmoid` or `hinge`. | +| `length_normalize` | bool | `true` | Normalise log-probs by sequence length. SimPO's signature feature. | +| `label_smoothing` | float | `0.0` | Smoothing on preference labels for noisy data. | + +## Compute and memory + +| Model | LoRA rank | `max_length` | Approx VRAM (QLoRA 4-bit) | +|---|---|---|---| +| 7B | 16 | 4096 | 9 GB | +| 13B | 16 | 4096 | 16 GB | +| 8B | 32 | 8192 | 18 GB | + +About 1.2× SFT memory — much lighter than DPO's 2×. + +## Choosing `beta` and `gamma` + +| Combination | Behaviour | +|---|---| +| `beta=2.0`, `gamma=1.0` | Default. Balanced. | +| `beta=2.5`, `gamma=1.4` | More aggressive preference shift. | +| `beta=1.5`, `gamma=0.5` | Gentler, closer to original SFT outputs. | + +:::warn +SimPO's `beta` is on a different scale than DPO's `beta`. Don't copy DPO hyperparameters as-is — start from SimPO defaults. +::: + +## Common pitfalls + +:::warn +**Overshooting on beta.** SimPO is more sensitive than DPO; high `beta` plus a small dataset produces a model that aggressively prefers chosen but loses general capability. Watch your benchmark scores during training. +::: + +:::warn +**Using SimPO without SFT first.** Same warning as DPO — start from a quality SFT checkpoint, not a raw base model. +::: + +## See also + +- [DPO](#/training/dpo) — the reference-based cousin; switch to SimPO when VRAM is tight. +- [ORPO](#/training/orpo) — combines SFT and preference loss in one stage. +- [Configuration Reference](#/reference/configuration) — full parameter list. diff --git a/docs/usermanuals/tr/compliance/annex-iv.md b/docs/usermanuals/tr/compliance/annex-iv.md new file mode 100644 index 00000000..c79c7d08 --- /dev/null +++ b/docs/usermanuals/tr/compliance/annex-iv.md @@ -0,0 +1,164 @@ +--- +title: Annex IV +description: EU AI Act Madde 11 teknik dokümantasyonu, eğitim koşunuzdan otomatik doldurulur. +--- + +# Annex IV + +EU AI Act'in (Tüzük (AB) 2024/1689) Annex IV bölümü, yüksek-riskli AI sistemleri için gereken sekiz bölümlü teknik dokümantasyonu tanımlar. ForgeLM bu artifact'ı otomatik üretir — `compliance.annex_iv: true` olan her koşunun ardından `artifacts/annex_iv.json`. + +## Sekiz bölüm + +| § | Bölüm | ForgeLM'in otomatik doldurduğu | +|---|---|---| +| 1 | Genel açıklama | Model adı, amaçlanan kullanım, coğrafyalar, sürüm. | +| 2 | Detaylı sistem açıklaması | Base model, trainer (SFT/DPO/...), veri seti özeti. | +| 3 | İzleme | Eval eşikleri, otomatik geri alma tetikleyicileri, trend izleme yapılandırması. | +| 4 | Risk yönetimi | Risk sınıflandırması, uygulanan azaltıcılar, kalıntı riskler. | +| 5 | Yaşam döngüsü | Eğitim zaman damgası, dataset sürümleri, kaynak referansları. | +| 6 | Uyumlaştırılmış standartlar | Listelenen uyumluluk çerçeveleri (EU AI Act, GDPR, ISO 27001). | +| 7 | AB uygunluk beyanı | İskelet; nihai aşamada bir insan tarafından imzalanır. | +| 8 | Pazara-sonrası izleme planı | Deployment surveillance config'ine referans. | + +## Konfigürasyon → Annex IV + +Annex IV'ün çoğu `compliance:` YAML bloğunuzdan doldurulur. Gerekli alanlar: + +```yaml +compliance: + annex_iv: true # ana anahtar + + # Bölüm 1: Genel açıklama + intended_purpose: "Çok dilli telekom müşteri-destek asistanı" + deployment_geographies: ["TR", "EU"] + responsible_party: "Acme Corp " + version: "1.2.0" + + # Bölüm 4: Risk sınıflandırması + risk_classification: "high-risk" # veya "minimal", "limited" + risk_assessment: + foreseeable_misuse: + - "Sosyal mühendislikte müşteri kimliği taklidi" + - "Sahte fatura üretimi" + mitigations: + - "Llama Guard S5 (iftira) kapısı zorunlu" + - "Ingest'te PII maskelenir" + residual_risks: + - "System prompt'a karşı adversarial jailbreak'ler" + + # Bölüm 6: Standartlar + standards: ["EU AI Act", "GDPR", "ISO 27001"] + + # Bölüm 8: Pazara-sonrası plan referansı + post_market_plan: "https://internal.acme.example/forgelm-monitoring" +``` + +Audit aşaması ([Veri Seti Denetimi](#/data/audit)) Bölüm 2'nin veri seti özetini ve Bölüm 5'in veri lineage'ını otomatik sağlar. + +## Çıktı yapısı + +`annex_iv.json` EU AI Act şemasını yakından takip eder: + +```json +{ + "schema_version": "annex_iv/1.0", + "section_1_general_description": { + "name": "Acme Customer Support v1.2.0", + "intended_purpose": "...", + "deployment_geographies": ["TR", "EU"], + "responsible_party": "Acme Corp ", + "version": "1.2.0" + }, + "section_2_detailed_system_description": { + "base_model": "Qwen/Qwen2.5-7B-Instruct", + "trainer": "dpo", + "datasets": [{ + "path": "data/preferences.jsonl", + "row_count": 12400, + "audit_report": "audit/data_audit_report.json", + "source_documents": "data/sources.json" + }], + "training_recipe": "configs/customer-support.yaml" + }, + "section_3_monitoring": { + "benchmark_floors": {"hellaswag": 0.55, "...": "..."}, + "safety_thresholds": {"S5": 0.30, "...": "..."}, + "trend_tracking": true + }, + "section_4_risk_management": { + "classification": "high-risk", + "foreseeable_misuse": [...], + "mitigations": [...], + "residual_risks": [...] + }, + "section_5_lifecycle": { + "trained_at": "2026-04-29T14:01:32Z", + "training_duration_seconds": 1892, + "config_hash": "sha256:deadbeef...", + "dataset_hashes": {...} + }, + "section_6_harmonised_standards": ["EU AI Act", "GDPR", "ISO 27001"], + "section_7_declaration_of_conformity": { + "status": "scaffold", + "signed_by": null, + "signed_at": null, + "notes": "Sunulmadan önce insan incelemesi ve imza gerekir." + }, + "section_8_post_market_plan": "https://internal.acme.example/forgelm-monitoring", + "manifest_sha256": "..." +} +``` + +## Tamper-evidence + +`annex_iv.json` da `manifest.json`'da hashlenir; pakettin diğer her artifact'ıyla yan yana. Manifest, değişmez paketin kanonik imzasıdır: + +```json +{ + "schema": "manifest/1.0", + "artifacts": { + "annex_iv.json": "sha256:abc123...", + "audit_log.jsonl": "sha256:def456...", + "data_audit_report.json": "sha256:789abc...", + "safety_report.json": "sha256:fedcba...", + "benchmark_results.json": "sha256:111222..." + }, + "generated_at": "2026-04-29T14:33:04Z" +} +``` + +Gerçek tamper-evidence için `manifest.json`'u ayrı bir write-once depoya gönderin (S3 Object Lock, HSM-imzalı ledger vb.). Toolkit artifact'ı üretir; operasyonel chain-of-custody sizin sorumluluğunuzdadır. + +## Annex IV doğrulama + +Bir Annex IV'ü "denetlemeye hazır" saymadan önce şemayı doğrulayın: + +```shell +$ forgelm verify-annex-iv checkpoints/run/artifacts/annex_iv.json +✓ schema valid +✓ all required fields present +✓ manifest checksums match +⚠ section_7 declaration unsigned (yeni koşular için beklenen) +``` + +`forgelm verify-annex-iv` komutu manifest hash'lerini de yeniden hesaplar ve üretimden sonra tahrif olup olmadığını kontrol eder. + +## Sık hatalar + +:::warn +**Bölüm 7'deki insan incelemesi adımını atlamak.** Uygunluk beyanı yasal bir belgedir. Otomatik üretilen iskelet imzasızdır ve yasal bir etkisi yoktur — sunmadan önce bir insan inceleyip imzalamalıdır. +::: + +:::warn +**ForgeLM çıktısını sertifikasyon olarak görmek.** ForgeLM kanıt üretir; sertifikasyon notified-body faaliyetidir. Belgelerimizin terminolojisi bunu yansıtır: "Annex-IV-tarzı artifact", "iskelet", "kanıt paketi" — asla "sertifikalı" değil. +::: + +:::tip +Yüksek-riskli deployment'larda Annex IV artifact'ını model registry'nizde model sürümleriyle birlikte versiyonlayın. Denetçiler Annex IV'ü release başına görmek ister, eğitim koşusu başına değil. +::: + +## Bkz. + +- [Uyumluluk Genel Bakış](#/compliance/overview) — paketin geri kalanı için bağlam. +- [Audit Log](#/compliance/audit-log) — append-only event log. +- [İnsan Gözetimi](#/compliance/human-oversight) — Madde 14. diff --git a/docs/usermanuals/tr/compliance/audit-log.md b/docs/usermanuals/tr/compliance/audit-log.md new file mode 100644 index 00000000..d6ec29af --- /dev/null +++ b/docs/usermanuals/tr/compliance/audit-log.md @@ -0,0 +1,142 @@ +--- +title: Audit Log +description: Eğitim, değerlendirme ve geri alma kararlarını append-only event log olarak tutar — Madde 12. +--- + +# Audit Log + +EU AI Act Madde 12, yüksek-riskli AI sistemlerinin operasyonel olarak ilgili olayların log'unu tutmasını gerektirir. ForgeLM'in `audit_log.jsonl` dosyası; eğitim başlangıcı, eval kapıları, otomatik geri alma kararları ve model export'unu kapsayan, append-only ve SHA-256-anchored bir olay dizisidir. + +## Format + +Satır başına bir JSON nesnesi: + +```jsonl +{"ts":"2026-04-29T14:01:32Z","seq":1,"event":"run_start","run_id":"abc123","config_hash":"sha256:dead..."} +{"ts":"2026-04-29T14:01:35Z","seq":2,"event":"data_audit_complete","verdict":"clean","..."} +{"ts":"2026-04-29T14:18:55Z","seq":3,"event":"training_epoch_complete","epoch":1,"loss":1.42} +{"ts":"2026-04-29T14:33:04Z","seq":4,"event":"benchmark_complete","verdict":"pass"} +{"ts":"2026-04-29T14:33:08Z","seq":5,"event":"safety_eval_complete","verdict":"pass"} +{"ts":"2026-04-29T14:33:10Z","seq":6,"event":"run_complete","exit_code":0,"prev_hash":"sha256:beef..."} +``` + +Her kayıtta: +- **`ts`** — ISO-8601 UTC zaman damgası. +- **`seq`** — koşu içinde monotonik sıra numarası (her koşuda sıfırlanır). +- **`event`** — olay tipi (aşağıda). +- **`prev_hash`** — önceki kaydın SHA-256'sı (tamper-evidence için zincirleme). +- Olaya özgü alanlar. + +## Olay tipleri + +| Olay | Ne zaman | +|---|---| +| `run_start` | Her `forgelm` çağrısının başında. | +| `config_validated` | `--dry-run` geçtikten sonra. | +| `data_audit_complete` | `forgelm audit` koşturulduktan sonra. | +| `training_epoch_complete` | Her eğitim epoch'undan sonra. | +| `training_step_milestone` | Konfigüre adım aralıklarında (varsayılan 1000). | +| `benchmark_complete` | Benchmark suite koşturulduktan sonra. | +| `safety_eval_complete` | Llama Guard skorlamasından sonra. | +| `auto_revert` | Otomatik geri alma tetiklendiğinde. | +| `human_approval_request` | `compliance.human_approval` engellediğinde. | +| `human_approval_granted` | Onay imzalandığında. | +| `model_exported` | `forgelm export` deploy edilebilir artifact yazdığında. | +| `run_complete` | Başarılı çıkışta. | +| `run_failed` | Sıfır olmayan çıkışta. | + +## Tasarım gereği append-only + +ForgeLM önceki log kayıtlarını asla yeniden yazmaz. Yeni olaylar sona eklenir. Zincirlenen `prev_hash` modifikasyonu tespit edilebilir kılar: N. kaydı değiştirirseniz N+1'den itibaren her kaydın `prev_hash` referansı yanlış olur. + +:::warn +**Konvansiyon, zorlama değil.** Toolkit append-only yazar ve zinciri hashler ama dosya filesystem'inizde — yazma erişimi olan herkes düzenleyebilir. Gerçek tamper-evidence için log'u ayrı bir write-once depoya gönderin (S3 Object Lock, ledger DB, HSM). Bu sizin operasyonel sorumluluğunuzdur. +::: + +## Bütünlük doğrulama + +```shell +$ forgelm verify-log checkpoints/run/artifacts/audit_log.jsonl +✓ 87 kayıt, tüm zaman damgaları monotonik +✓ tüm prev_hash zincirleri geçerli +✓ seq numaralarında boşluk yok +``` + +`verify-log` zincir kırığı raporlarsa, log üretimden sonra değiştirilmiş demektir. Kanıt olarak işlem görmeden önce araştırın. + +## Koşu başı vs proje başı + +Her eğitim koşusu kendi `audit_log.jsonl`'ını o koşunun `artifacts/` dizininde üretir. Proje başı geçmiş için ForgeLM proje kökünde `.forgelm/global-audit-log.jsonl`'ı da tutar (varsayılan gitignore'da — commit'e karar siz verin). + +Global log *koşular-arası* olayları kaydeder: + +- Projedeki her koşu için `run_start` ve `run_complete`. +- Manuel model terfi ve geri alma. +- Yapılandırma değişiklikleri (ForgeLM yeni YAML sürümlerini tespit ettiğinde). + +## Konfigürasyon + +```yaml +compliance: + audit_log: + enabled: true + path: "${output.dir}/artifacts/audit_log.jsonl" + step_milestone_interval: 1000 # her N adımda step olayı + include_config_dump: true # run_start olayında tam config + redact_secrets: true # dump'lanmış config'te api key'leri maskele +``` + +## Dış depolara yönlendirme + +Üretimde tamper-evidence için log kayıtlarını ayrı bir write-once veya append-only depoya yönlendirin: + +```yaml +compliance: + audit_log: + forward_to: + - type: "s3" + bucket: "compliance-audit-logs" + prefix: "forgelm/{run_id}/" + object_lock: true + - type: "syslog" + host: "audit.internal:514" + protocol: "tcp" +``` + +ForgeLM her yayınlanan olayı konfigüre hedeflere yansıtır. Dış depo erişilemezse koşu başarısız olur (audit olaylarını sessizce düşürmemek için). + +## Log'u okuma + +İnsan incelemesi için: + +```shell +$ jq -r '.event + "\t" + .ts' checkpoints/run/artifacts/audit_log.jsonl +run_start 2026-04-29T14:01:32Z +config_validated 2026-04-29T14:01:33Z +data_audit_complete 2026-04-29T14:01:35Z +training_epoch_complete 2026-04-29T14:18:55Z +... +run_complete 2026-04-29T14:33:10Z +``` + +Dashboard için JSONL doğal olarak Loki, OpenSearch veya herhangi bir log-aggregation aracına akar. + +## Sık hatalar + +:::warn +**"Bir typo'yu düzeltmek için" log'u editlemek.** Yapmayın. Kozmetik düzenlemeler bile zincir hash'ini bozar ve audit değerini düşürür. Gerçekten bilgi düzeltmek gerekirse `corrects_seq` referansıyla yeni bir `correction` olayı ekleyin. +::: + +:::warn +**Log'u sadece eğitim host disklerinde tutmak.** Disk arızası = kaybedilen audit kanıtı. Her zaman dayanıklı depolamaya yönlendirin (versiyonlu + Object Lock'lu S3, ledger DB). +::: + +:::tip +**Üretimde koşular arası log zincirleyin.** Bir checkpoint'i üretime terfi ettirdiğinizde önceki sürümü referans alan `model_promoted` olayı ekleyin. Denetçiler eğitimden deployment'a kesintisiz chain-of-custody görmeyi sever. +::: + +## Bkz. + +- [Annex IV](#/compliance/annex-iv) — audit log'a işaret eden teknik doküman. +- [Otomatik Geri Alma](#/evaluation/auto-revert) — `auto_revert` olaylarını üretir. +- [İnsan Gözetimi](#/compliance/human-oversight) — onay olaylarını üretir. diff --git a/docs/usermanuals/tr/compliance/gdpr.md b/docs/usermanuals/tr/compliance/gdpr.md new file mode 100644 index 00000000..09cd20fb --- /dev/null +++ b/docs/usermanuals/tr/compliance/gdpr.md @@ -0,0 +1,151 @@ +--- +title: GDPR / KVKK +description: Veri koruma uyumluluğu — PII minimizasyonu, veri sahibi hakları ve audit kanıtı. +--- + +# GDPR / KVKK + +GDPR (Avrupa) ve KVKK (Türkiye), eğitimde kullanılan kişisel verilere koruma gereklilikleri getirir. ForgeLM'in rolü: kişisel verinin eğitime girmesini en başta engellemek, ne girdiğini belgelemek ve veri sahibi talepleri için kanıt üretmek. + +## GDPR / KVKK eğitim verisinde ne ister + +| İlke | Madde | Eğitim için anlamı | +|---|---|---| +| **Hukuka uygunluk** | GDPR Md. 5(1)(a) | Kişisel veri işlemek için hukuki bir dayanağınız olmalı. | +| **Amaç sınırlaması** | GDPR Md. 5(1)(b) | A amacı için toplanan veri, ilişkisiz B amacı için kullanılamaz. | +| **Veri minimizasyonu** | GDPR Md. 5(1)(c) | Gerekenden fazla kişisel veri toplamayın veya saklamayın. | +| **Doğruluk** | GDPR Md. 5(1)(d) | Veriyi doğru tutun; yanlış veriyi düzeltin veya silin. | +| **Saklama sınırlaması** | GDPR Md. 5(1)(e) | Gerekenden uzun saklamayın. | +| **Bütünlük & gizlilik** | GDPR Md. 5(1)(f) | Yetkisiz erişime karşı koruyun. | +| **Hesap verebilirlik** | GDPR Md. 5(2) | Uyumu gösterebilmelisiniz. | + +KVKK (Türkiye) bu ilkeleri yakından yansıtır. + +## ForgeLM her birini nasıl ele alıyor + +### Veri minimizasyonu (Md. 5(1)(c)) + +Ingest'te PII maskeleme kişisel tanımlayıcıları placeholder'larla değiştirir: + +```yaml +ingestion: + pii_mask: + enabled: true + locale: "tr" + categories: ["email", "phone", "iban", "id_tr"] +``` + +Veri JSONL'a düştüğünde tanımlanabilir özneler kaldırılmıştır. Bkz. [PII Maskeleme](#/data/pii-masking). + +### Hesap verebilirlik (Md. 5(2)) + +Her audit aşağıdakileri belgeleyen `data_audit_report.json` üretir: + +- Tespit edilen PII kategorileri ve sayıları (maskelemeden önce). +- Kaynak atfı (her satırın hangi dokümandan geldiği). +- Kalite ve dil dağılımı. +- Tamper-evidence için SHA-256 manifest. + +Bu raporlar Annex IV paketine akar. Regülatör "eğitim setinizde hangi kişisel veriler vardı?" diye sorduğunda yapılandırılmış cevabınız olur. + +### Saklama sınırlaması (Md. 5(1)(e)) + +ForgeLM ham kullanıcı verisini saklamaz — sizin kontrol ettiğiniz JSONL artifact'lar üretir. Otomatik saklama uygulanması için: + +```yaml +ingestion: + retention: + raw_documents: + ttl_days: 90 # N gün sonra orijinalleri otomatik sil + audit_reports: + ttl_days: 365 +``` + +(Asıl silme depolama katmanınızın sorumluluğu; ForgeLM sadece amaçlanan TTL'yi audit log'a kaydeder.) + +## Veri sahibi talepleri + +En sık talep tipleri ve ForgeLM nasıl yardım eder: + +### Erişim hakkı (Md. 15) + +"Hakkımda hangi kişisel verileri tutuyorsunuz?" + +Eğitim verinizde reverse-PII koşturun: + +```shell +$ forgelm reverse-pii --query "ali@example.com" data/*.jsonl +Maskelenmiş veride eşleşme bulunamadı. +``` + +PII ingest'te maskelendiği için modelden belirli birinin verisi geri çıkarılamaz. Audit raporu bunu teyit eder. + +### Silme hakkı (Md. 17) + +"Verilerimi silin." + +Bir kişinin verisi eğitim setinizdeydi: +1. Maskelenmiş JSONL kimlik bilgilerini içermiyor — zaten minimize edilmiş. +2. Ham kaynak dokümanlar hâlâ içerebilir — ham deponuzdan düşürün ve gerekirse yeniden ingest edin. +3. Model bazı detayları ezberlemiş olabilir — aşağıdaki "model-seviyesi silme"ye bakın. + +### Model-seviyesi silme + +LLM'ler eğitimden nadir string'leri ezberleyebilir. PII maskelemeyle bile deploy edilmiş bir modelden tüm izleri kaldırmak zordur. ForgeLM'in savunmaları: + +- **Ezberi önle:** PII maskeleme, deduplikasyon (ezberlenen veri genelde tekrarlanan veridir). +- **Ezberi tespit et:** Audit aşaması bilinen PII pattern'leriyle örtüşen satırları flagler. +- **Son çare yeniden eğitim:** Maskelemeye rağmen belirli bir öznenin verisi sızdıysa, o kaynak olmadan yeniden eğitin. + +Sıfır-tolerans senaryolarda (sağlık, hukuk) PII maskelemeyi eğitimden önce manuel inceleme ile birleştirin. + +## DPIA (Veri Koruma Etki Değerlendirmesi) + +Yüksek-riskli işleme için GDPR Md. 35 DPIA gerektirir. ForgeLM DPIA'nızı yazmaz, ama audit paketi girdi sağlar: + +- Risk sınıflandırması → `compliance.risk_classification`'dan. +- Kişisel veri envanteri → `data_audit_report.json`'dan. +- Uygulanan azaltıcılar → `compliance.risk_assessment.mitigations`'dan. +- Kalıntı riskler → `compliance.risk_assessment.residual_risks`'tan. + +Bunları tüketen DPIA şablonu `docs/qms/dpia-template.md`'de. + +## Konfigürasyon referansı + +```yaml +compliance: + data_protection: + framework: "GDPR" # GDPR | KVKK | both + lawful_basis: "legitimate-interest" # consent | contract | legal-obligation | ... + purpose: "X için müşteri-destek asistanı" + data_controller: "Acme Corp" + data_subjects: "telekom müşterileri" + retention_basis: "model yaşam döngüsü (~3 yıl) artı audit dönemi" + international_transfers: + enabled: false # eğitim verisi sınır geçiyorsa true + safeguards: "Standart Sözleşme Hükümleri 2021/914" +``` + +## Sık hatalar + +:::warn +**PII maskelemeyi DPIA-yerine koymak.** Maskeleme teknik bir azaltıcıdır, hukuki değerlendirme değildir. DPIA, risklerin, azaltıcıların ve kalıntı zararın belgelenmiş analizidir — yüksek-riskli işleme için ayrıca gereklidir. +::: + +:::warn +**İç verilerde audit'i atlamak.** İç veri, istenmeden kişisel veri ifşasının en yaygın kaynağıdır (çalışan kayıtları müşteri-destek eğitimine sızar). Her şeyi denetleyin. +::: + +:::warn +**Uluslararası transferler.** Eğitim veriniz yargı sınırlarını aşıyorsa (Türk verisi AB'de eğitiliyor, AB verisi ABD'de eğitiliyor), ek koruma önlemleri uygulanır. `international_transfers.enabled: true` ayarlayın ve koruma önlemlerini belgeleyin. +::: + +:::tip +Sağlık ve finans gibi sektörlerde *ilk eğitim öncesi* gizlilik uzmanına danışın. ForgeLM varsayılanları makuldür ama sektöre-özgü hukuki incelemeyi yerine geçemez. +::: + +## Bkz. + +- [PII Maskeleme](#/data/pii-masking) — teknik uygulama. +- [Uyumluluk Genel Bakış](#/compliance/overview) — geniş bağlam. +- [Annex IV](#/compliance/annex-iv) — paketlenmiş compliance kanıtı. diff --git a/docs/usermanuals/tr/compliance/human-oversight.md b/docs/usermanuals/tr/compliance/human-oversight.md new file mode 100644 index 00000000..3fab3ba0 --- /dev/null +++ b/docs/usermanuals/tr/compliance/human-oversight.md @@ -0,0 +1,164 @@ +--- +title: İnsan Gözetimi +description: Bir insan inceleyip imzalayana kadar model terfisini engelleyin — Madde 14 kapısı. +--- + +# İnsan Gözetimi + +EU AI Act Madde 14, yüksek-riskli AI sistemlerinin insan gözetimi imkânı sağlamasını gerektirir. ForgeLM bunu opsiyonel bir config kapısı olarak uygular: `compliance.human_approval: true` olduğunda model terfisi bir insan onay imzalayana kadar engellenir. + +## Kapı nasıl çalışır + +```mermaid +sequenceDiagram + participant Train as forgelm + participant Eval as Eval pipeline + participant Approver as İnsan onaylayıcı + participant Audit as Audit log + participant Output as Çıktı dizini + + Train->>Eval: Eğitim tamam, eval koştur + Eval->>Eval: Benchmark + güvenlik geçti + Eval->>Audit: "human_approval_request" ekle + Eval->>Approver: Webhook + yapılandırılmış istek + Approver-->>Eval: Onayı imzala (CLI / webhook callback) + Eval->>Audit: İmzalı "human_approval_granted" ekle + Eval->>Output: Checkpoint'i terfi ettir +``` + +İmza olmadan checkpoint "pending" durumda kalır ve koşu exit kodu 4 (bekleme) ile çıkar. Bu bir *başarısızlık değil* — inceleme için kontrollü bir bekletme. + +## Konfigürasyon + +```yaml +compliance: + human_approval: true + approval: + request_webhook: "${SLACK_WEBHOOK}" # opsiyonel bildirim + signature_method: "cli" # cli | webhook | api + timeout_hours: 48 # sonra otomatik fail + require_role: "ml-compliance-lead" # kim onaylayabilir + quorum: 1 # gerekli onaylayıcı sayısı +``` + +## İmza yöntemleri + +### CLI (varsayılan) + +Trainer eval'den sonra durur ve yazdırır: + +```text +[2026-04-29 14:33:10] İnsan onayı gerekli. + Run ID: abc123 + Bundle: checkpoints/run/artifacts/ + + Onaylamak için: forgelm approve --run-id abc123 --reviewer "Cemil " + Reddetmek için: forgelm approve --run-id abc123 --reject --reason "..." +``` + +Reviewer artifacts dizinine erişimi olan herhangi bir makineden onay komutunu çalıştırır. ForgeLM SSH key signing veya env-set token üzerinden kimliği doğrular, audit log'u imzalar ve terfiyi sürdürür. + +### Webhook callback + +Dahili onay sistemleriyle entegrasyon için: + +```yaml +approval: + signature_method: "webhook" + webhook_url: "https://internal.example/approvals/{run_id}/decide" +``` + +Trainer durur ve artifact paketini webhook'unuza POST'lar. Sisteminiz insan incelemesini halleder ve imzalı JWT ile ForgeLM'in resume endpoint'ine geri POST'lar. + +### API + +Self-servis otomasyon için (ör. dashboard'unuzda "bu koşuyu terfi ettir" düğmesi): + +```yaml +approval: + signature_method: "api" + resume_token: "${FORGELM_RESUME_TOKEN}" +``` + +Dashboard'unuz doğrudan ForgeLM'in resume endpoint'ini koşu ID'si ve reviewer kimliğiyle çağırır. İmzalar audit log'a kaydedilir. + +## Onay imzasında ne var + +Her onay (veya red) `audit_log.jsonl`'a eklenir: + +```json +{ + "ts": "2026-04-29T15:18:42Z", + "seq": 87, + "event": "human_approval_granted", + "run_id": "abc123", + "reviewer": "Cemil Ilik ", + "role": "ml-compliance-lead", + "method": "cli", + "signature": "ed25519:...", + "comment": "Güvenlik raporunu inceledim; bu deployment için S5 max 0.04 kabul edilebilir.", + "artifact_hash": "sha256:..." +} +``` + +`signature` artifact paketinin `manifest.json` hash'i üzerine — reviewer'ın *tam olarak* üretileni gördüğünü tasdik eder. + +## Quorum (çoklu reviewer) + +Yüksek-riskli deployment'lar için birden çok onaylayıcı isteyin: + +```yaml +approval: + quorum: 2 + require_role: "ml-compliance-lead" +``` + +Her onaylayıcı CLI komutunu bağımsız çalıştırır. Quorum imzaladıktan (veya biri reddettikten) sonra terfi olur. + +## Timeout + +`timeout_hours` sonrası imzasız koşu yapılandırılmış olayla exit 4 + auto-fail: + +```json +{"event": "human_approval_timeout", "expired_at": "2026-04-30T14:33:10Z"} +``` + +Varsayılan 48 saat. "Timeout yok — sonsuza kadar bekle" için 0 (CI'da önerilmez). + +## Bekleyen koşuları inceleme + +```shell +$ forgelm approvals --pending +RUN_ID REQUESTED_AT ARTIFACTS EXPIRES +abc123 2026-04-29T14:33Z checkpoints/run/artifacts/ 47s sonra +def456 2026-04-29T09:12Z checkpoints/sft-only/artifacts/ 42s sonra +``` + +```shell +$ forgelm approvals --show abc123 +... audit, benchmark'lar, güvenlik, model card dahil tam artifact özeti ... +``` + +## Sık hatalar + +:::warn +**"Pipeline'ı açmak için" CI'da otomatik onaylamak.** İnsan gözetimi amacını yok eder. Kapı yolunuzdaysa ya aşırı kullanıyorsunuz (yüksek-riskli olmayan koşularda kapatın) ya da reviewer'ları yetersiz. +::: + +:::warn +**Reviewer'ın kaşeleyici olması.** İmza bilgilendirilmiş olmalı. Reviewer'ın gerçekten ne için imzaladığını görmesi için onay akışında tam artifact özetini gösterin. +::: + +:::warn +**Üretim kararları için quorum yok.** Yüksek-riskli üretim deployment'ları için tek-reviewer onayı yetersizdir. Her zaman quorum >= 2 isteyin. +::: + +:::tip +**Onay CLI'sını erişilebilir yapın.** Reviewer'lar onay vermek için eğitim host'una SSH'lamak zorunda kalmamalı. Artifacts dizinini paylaşımlı depolamada kurun, reviewer'lar `forgelm approve`'u kendi makinelerinden çalıştırsın. +::: + +## Bkz. + +- [Audit Log](#/compliance/audit-log) — imzaların kaydedildiği yer. +- [Annex IV](#/compliance/annex-iv) — Bölüm 7 beyanı insanlar tarafından imzalanır, toolkit tarafından değil. +- [Webhook'lar](#/operations/webhooks) — onay istekleri Slack/Teams uyarıları fırlatabilir. diff --git a/docs/usermanuals/tr/compliance/model-card.md b/docs/usermanuals/tr/compliance/model-card.md new file mode 100644 index 00000000..54714dcf --- /dev/null +++ b/docs/usermanuals/tr/compliance/model-card.md @@ -0,0 +1,160 @@ +--- +title: Model Card +description: Otomatik üretilen şeffaflık dokümantasyonu — Madde 13. +--- + +# Model Card + +EU AI Act Madde 13 şeffaflığı zorunlu kılar: deploy edilen AI sistemleri net dokümantasyonla birlikte sunulmalıdır — yetenekler, sınırlar, amaçlanan kullanım, eğitim verisi. ForgeLM her başarılı koşudan sonra HuggingFace-uyumlu `README.md` model card'ı üretir. + +## ForgeLM'in otomatik doldurduğu + +| Bölüm | Kaynak | +|---|---| +| **Model detayları** | `model.name_or_path`, eğitim paradigması, sürüm. | +| **Amaçlanan kullanım** | `compliance.intended_purpose`. | +| **Kapsam dışı kullanım** | `compliance.risk_assessment.foreseeable_misuse`. | +| **Eğitim verisi** | Her `datasets:` girdisinin audit özeti. | +| **Eğitim prosedürü** | YAML config snapshot. | +| **Değerlendirme** | `benchmark_results.json` özeti. | +| **Güvenlik** | `safety_report.json` özeti. | +| **Sınırlamalar** | `compliance.risk_assessment.residual_risks`. | +| **Atıf** | Sentetik veri kullanıldıysa teacher modeli atıfla anar. | +| **Lisans** | `compliance.license` alanından. | + +Çıktı, HuggingFace Hub'a yüklenmeye hazır `checkpoints/run/README.md` dosyasıdır. + +## Örnek çıktı + +```markdown +# Acme Customer Support v1.2.0 + +ForgeLM 0.5.2 kullanılarak Qwen2.5-7B-Instruct'tan fine-tune edilmiş +müşteri-destek asistanı. + +## Model detayları + +- **Base model:** Qwen/Qwen2.5-7B-Instruct +- **Fine-tuning paradigması:** SFT → DPO +- **Parametre-verimli yöntem:** QLoRA (rank 16, alpha 32, DoRA açık) +- **Eğitim:** 2026-04-29 +- **Diller:** Türkçe, İngilizce +- **Lisans:** Apache 2.0 + +## Amaçlanan kullanım + +Türk telekom için çok dilli müşteri-destek asistanı. Authenticated +kullanıcı oturumlarında faturalandırma, plan ve teknik destek +sorularını yanıtlamak üzere deploy edilir. + +## Kapsam dışı kullanım + +Bu model şunlar için **uygun değildir**: +- Sosyal mühendislikte müşteri kimliği taklidi. +- Sahte fatura üretimi. +- Türkçe/İngilizce dil çiftinin dışındaki kullanım. +- Authentication veya rate-limiting olmadan kullanım. + +## Eğitim verisi + +- 12,400 tercih satırı (`data/preferences.jsonl`) + - Audit verdict: warnings (12 PII orta-seviye flag, ingest'te maskelendi) + - Split-arası örtüşme: 0 + - Dil dağılımı: %99.2 TR, %0.5 EN + +## Eğitim prosedürü + +Tam config `config_snapshot.yaml`'da. Öne çıkanlar: + +- Trainer: `dpo` +- Beta: 0.1 +- Learning rate: 5e-6 +- Epoch: 1 +- Batch size: 2 (32 etkili, accumulation ile) + +## Değerlendirme + +| Görev | Puan | Floor | Verdict | +|---|---|---|---| +| hellaswag | 0.617 | 0.55 | geçti | +| truthfulqa | 0.482 | 0.45 | geçti | +| arc_easy | 0.74 | 0.70 | geçti | + +## Güvenlik + +S1–S14 üzerinde Llama Guard 3 8B skorlama: + +- Tüm bloklu kategoriler (S1, S2, S5, S10) pre-train baseline'ın 0.05 içinde. +- High severity'de kategori yok. + +Tam rapor `artifacts/safety_report.json`'da. + +## Sınırlamalar + +- System prompt'a karşı adversarial jailbreak'ler ara sıra başarılı olabilir. +- 4096 token üzerindeki konuşma turlarında performans düşer. +- Model sadece Türkçe-İngilizce iki dilli veri üzerinde eğitildi — başka + dil desteği yok. + +## Uyumluluk + +- EU AI Act: `artifacts/annex_iv.json`'da Annex IV teknik dokümantasyonu +- GDPR: PII ingest'te maskelendi; eğitim verisi tanımlanabilir özne tutmaz +- Audit log: `artifacts/audit_log.jsonl` + +Ticari kullanım için bkz. `LICENSE`. + +## Atıf + +Bu modeli kullanırsanız lütfen şöyle atıf yapın: + +``` +@misc{acme2026, + title = {Acme Customer Support v1.2.0}, + author = {Acme Corp}, + year = {2026}, + note = {ForgeLM 0.5.2 ile fine-tune edildi} +} +``` +``` + +## Konfigürasyon + +```yaml +output: + model_card: true # varsayılan + model_card_template: null # özel Jinja2 template yolu +``` + +Marka için varsayılan template'i override edin: + +```yaml +output: + model_card_template: "templates/acme-card.j2" +``` + +Template aynı veriyi alır — sadece farklı render eder. + +## Manuel eklemeler + +Varsayılan model card ForgeLM'in otomatik belirleyebildiklerini kapsar. Manuel eklemeler (teşekkürler, özel uyarılar) için koşudan sonra üretilen `README.md`'ye `## Notlar` bölümü ekleyin. Audit log bunu `model_card_amended` olayı olarak işler. + +## Sık hatalar + +:::warn +**Önceki koşulardan kalmış model card.** Her koşu `README.md`'yi üzerine yazar. Önceki sürümü manuel düzenlediyseniz o düzenlemeler kaybolur. Koşular arası kalıcı olması gereken eklemeler için onları `compliance.notes` YAML alanına koyun. +::: + +:::warn +**`compliance.license`'ı unutmak.** Olmadan otomatik üretilen card "Lisans: belirtilmemiş" gösterir; çoğu dahili inceleme süreci başarısız olur. Lisansı açıkça ayarlayın. +::: + +:::tip +HuggingFace Hub yayını için ForgeLM'in model card'ı HuggingFace'in standart front-matter formatını kullanır — `language:`, `license:`, `tags:` vb. — Hub UI'da doğru render olur. +::: + +## Bkz. + +- [Annex IV](#/compliance/annex-iv) — Madde 11 kardeşi. +- [Uyumluluk Genel Bakış](#/compliance/overview) — bağlam. +- [Konfigürasyon Referansı](#/reference/configuration) — `output.model_card` alanı. diff --git a/docs/usermanuals/tr/compliance/overview.md b/docs/usermanuals/tr/compliance/overview.md new file mode 100644 index 00000000..3fdd7ae7 --- /dev/null +++ b/docs/usermanuals/tr/compliance/overview.md @@ -0,0 +1,111 @@ +--- +title: Uyumluluk Genel Bakış +description: ForgeLM EU AI Act, GDPR ve ISO 27001 gerekliliklerini eğitim hattına nasıl eşler. +--- + +# Uyumluluk Genel Bakış + +ForgeLM, eğitim hatlarını sadece bir CTO'ya değil, bir regülatöre savunması gereken ekipler için yapıldı. Her başarılı (veya başarısız) koşu, EU AI Act Madde 9-17'ye, GDPR Madde 5'e ve ISO 27001 kontrol hedeflerine temiz şekilde eşlenen yapılandırılmış bir kanıt paketi üretir. + +```mermaid +flowchart TD + Run[Eğitim koşusu] --> Audit[Veri denetimi] + Run --> Train[Eğitim + checkpoint] + Run --> Eval[Eval + güvenlik] + Run --> Doc[Otomatik model card] + + Audit --> A10[Madde 10
Veri yönetimi] + Train --> A12[Madde 12
Audit log] + Eval --> A9[Madde 9
Risk yönetimi] + Eval --> A15[Madde 15
Doğruluk] + Doc --> A13[Madde 13
Şeffaflık] + Audit --> A11[Madde 11
Annex IV] + Train --> A11 + Eval --> A11 + + classDef artifact fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef article fill:#161a24,stroke:#f97316,color:#e6e7ec + classDef start fill:#1c2030,stroke:#22c55e,color:#e6e7ec + class Run start + class Audit,Train,Eval,Doc artifact + class A9,A10,A11,A12,A13,A15 article +``` + +## Üretilen şeyler + +`compliance.annex_iv: true` olan her koşu artifacts dizini üretir: + +```text +checkpoints/run/artifacts/ +├── annex_iv.json ← Madde 11 — teknik dokümantasyon +├── audit_log.jsonl ← Madde 12 — append-only event log +├── data_audit_report.json ← Madde 10 — veri yönetimi kanıtı +├── safety_report.json ← Madde 9 + 15 — risk + güvenlik +├── benchmark_results.json ← Madde 15 — doğruluk +├── conformity_declaration.md ← Madde 16 — beyan iskeleti +└── manifest.json ← Yukarıdaki her artifact üzerinde SHA-256 +``` + +Bu paket compliance incelemeleri için teslim edilebilir. İçindeki her dosya `manifest.json`'da tamper-evidence için hashlenmiştir. + +## ForgeLM'in karşıladığı maddeler + +| Madde | Konu | ForgeLM nasıl | +|---|---|---| +| **9** | Risk yönetimi | Otomatik geri alma + eşik kapıları + trend izleme. | +| **10** | Veri yönetimi | `forgelm audit` veri seti başına yönetişim kanıtı üretir. | +| **11** | Teknik dokümantasyon | `annex_iv.json` dolu Annex IV. | +| **12** | Kayıt tutma | Eğitim başlangıcı, eval kapıları, geri alma kararlarını kapsayan append-only `audit_log.jsonl`. | +| **13** | Şeffaflık | Otomatik üretilen model card; yetenekleri, sınırları, eğitim özetini listeler. | +| **14** | İnsan gözetimi | Opsiyonel `compliance.human_approval: true` insan imzalayana kadar terfi engeller. | +| **15** | Doğruluk ve sağlamlık | Benchmark kapıları + güvenlik eval + cybersec (ingest'te PII / sırlar). | +| **16-17** | Uygunluk ve QMS | Beyan iskeleti + `docs/qms/`'deki QMS SOP'ları. | + +Tam kod referansları için sitenin [Compliance sayfası](compliance.html). + +## ForgeLM'in iddia *etmediği* + +:::warn +ForgeLM Annex IV tarzı teknik dokümantasyon **üretir**. Sisteminizi AI Act kapsamında bir yüksek-riskli AI sistemi olarak **sertifikalandırmaz** — bu, herhangi bir toolkit'in kapsamı dışındaki bir notified-body veya öz-değerlendirme faaliyetidir. + +Audit log konvansiyonel olarak append-only ve SHA-256-anchored. Gerçek tamper-evidence için log'u ayrı, write-once depoya (S3 Object Lock, ledger DB) göndermeniz gerekir. Toolkit artifact'ı üretebilir; chain-of-custody operasyonel sorumluluğunuzdur. + +PII / sırlar regex setleri tasarım gereği muhafazakar — false-negative'ları false-positive'lara tercih eder. Yüksek riskli corpus için manuel inceleme ile birlikte kullanın. +::: + +## Compliance artifact'larını etkinleştir + +YAML'da: + +```yaml +compliance: + annex_iv: true + data_audit_artifact: "./audit/data_audit_report.json" + human_approval: true # opsiyonel Madde 14 kapısı + intended_purpose: "Türk telekom için müşteri-destek asistanı" + risk_classification: "high-risk" + deployment_geographies: ["TR", "EU"] + responsible_party: "Acme Corp " +``` + +`compliance:` bloğundan her alan `annex_iv.json`'a akar. Gerekli alanlar config yüklenirken doğrulanır. + +## Operasyonel sorumluluklar (siz, ForgeLM değil) + +Toolkit kanıt üretir; insanlar sertifikasyonu üretir. Ekibiniz şunlardan sorumlu: + +- Üretime giden her koşunun audit paketini incelemek. +- Audit log'u tamper-evidence için write-once depoya göndermek. +- Gerektiğinde notified-body ile uygunluk değerlendirmesi yapmak. +- Model deploy edildikten sonra post-market monitoring'i sürdürmek. +- Veri sahibi taleplerini (GDPR Madde 15-22) ele almak. + +`docs/qms/`'deki ForgeLM QMS SOP'ları operasyonel tarafı kapsar. + +## Bkz. + +- [Annex IV](#/compliance/annex-iv) — Madde 11 artifact spec. +- [Audit Log](#/compliance/audit-log) — Madde 12. +- [İnsan Gözetimi](#/compliance/human-oversight) — Madde 14. +- [Model Card](#/compliance/model-card) — Madde 13. +- [GDPR / KVKK](#/compliance/gdpr). diff --git a/docs/usermanuals/tr/concepts/alignment-overview.md b/docs/usermanuals/tr/concepts/alignment-overview.md new file mode 100644 index 00000000..3535f10a --- /dev/null +++ b/docs/usermanuals/tr/concepts/alignment-overview.md @@ -0,0 +1,121 @@ +--- +title: Alignment Yığını +description: SFT, DPO, SimPO, KTO, ORPO ve GRPO nasıl bir araya gelir — ve ne zaman hangisi. +--- + +# Alignment Yığını + +Modern LLM fine-tuning'i artık tek bir algoritma değil — her biri farklı bir problemi ele alan post-training paradigmaları *yığını*. ForgeLM her altısını tek bir deklaratif arayüzün arkasında sunar; doğru aracı pipeline'ı yeniden yazmadan seçersiniz. + +```mermaid +flowchart TD + Base[Temel model
ör. Qwen 2.5 / Llama 3] + SFT[SFT
format & içerik] + DPO[DPO
tercih hizalaması] + SimPO[SimPO
tercih, ref-free] + KTO[KTO
ikili geri bildirim] + ORPO[ORPO
SFT+DPO birleşik] + GRPO[GRPO
akıl yürütme RL] + Out[Üretime hazır
hizalanmış model] + + Base --> SFT + Base --> ORPO + Base --> GRPO + SFT --> DPO + SFT --> SimPO + SFT --> KTO + DPO --> Out + SimPO --> Out + KTO --> Out + ORPO --> Out + GRPO --> Out + + classDef base fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef sft fill:#161a24,stroke:#22c55e,color:#e6e7ec + classDef pref fill:#161a24,stroke:#f97316,color:#e6e7ec + classDef done fill:#1c2030,stroke:#fb923c,color:#e6e7ec + class Base base + class SFT,ORPO,GRPO sft + class DPO,SimPO,KTO pref + class Out done +``` + +## Alignment'ın çözdüğü üç problem + +### Problem 1: Format + +Bir base model metni tamamlayabilir ama talimat takip etmez, chat turlarını kullanmaz, system prompt'u korumaz ve ne zaman duracağını bilmez. **SFT** bunu çözer: istediğiniz formatın örnekleriyle eğitin. + +### Problem 2: Tercihler + +SFT'den sonra model iyi formatta çıktı üretir ama kalite değişken — bazen kendinden emin, bazen kaçamak, bazen ayrıntıya boğulmuş. **DPO**, **SimPO**, **KTO** ve **ORPO** modeli tercih edilen çıktılara hizalar. + +Farklar: +- **DPO** — referans modele karşı `(chosen, rejected)` çiftlerinden öğrenir. En çok çalışılmış, en kararlı. +- **SimPO** — DPO ile aynı ama referans modeli atlar. Daha az bellek, biraz daha az kararlılık. +- **KTO** — ikili `(prompt, response, iyi mi?)` sinyallerinden öğrenir. Sadece thumbs-up/down geri bildiriminiz varsa kullanın. +- **ORPO** — SFT ve tercih kaybını tek geçişte birleştirir. Daha hızlı wall-clock; ayrı aşamalardan daha az esneklik. + +### Problem 3: Akıl yürütme + +Bazı görevler (matematik, kod, çok adımlı mantık) ikili tercihlerden değil akıl yürütme izleri üzerinde RL'den faydalanır. **GRPO** modelin kendi çıktıları üzerinde bir reward fonksiyonunu maksimize etmesini öğretir; format ve uzunluk ödülleri yerleşik. + +## Tipik bir üretim sırası + +```mermaid +sequenceDiagram + participant Base as Temel model + participant SFT as SFT aşaması + participant DPO as DPO aşaması + participant Eval as Eval & güvenlik + participant Prod as Üretim + + Base->>SFT: 12K talimat çifti + SFT->>DPO: SFT checkpoint (yardımcı ama sıkıcı) + DPO->>Eval: 3K tercih çifti + Eval->>Eval: lm-eval-harness + Llama Guard + Eval->>Prod: Eşikleri geç → terfi + Eval->>SFT: Regresyon → otomatik geri al +``` + +Çoğu ekip iki aşamada üretime ulaşır: format ve içerik için SFT, sonra tercihleri keskinleştirmek için DPO/SimPO/KTO. ORPO, wall-clock hızı gerektiren ve her iki tür veriniz hazır olduğunda ikisini bir aşamaya çöker. + +## Bir bakışta ödünleşim + +| Aşama | Gerekli veri | Bellek | Kararlılık | Atlama zamanı | +|---|---|---|---|---| +| SFT | Prompt-completion çifti | 1× | Kararlı | Asla — neredeyse her zaman gerekli | +| DPO | Chosen-rejected çifti | 2× | Kararlı | Tercih veriniz yoksa | +| SimPO | Chosen-rejected çifti | 1.2× | Orta | VRAM bolsa, DPO tercih edin | +| KTO | İkili thumbs-up/down | 1.5× | Orta | Eşli tercihiniz varsa (DPO kullanın) | +| ORPO | Hem çiftler hem tercihler | 1.5× | Kararlı | SFT ve DPO'yu ayrı deney olarak istiyorsanız | +| GRPO | Reward fonksiyonu veya reward modeli | 2-3× | Hassas | Akıl yürütme dışı görevler | + +:::tip +**SFT'yi atlamayın.** Mükemmel tercih veriniz olsa bile önce SFT formatı öğretsin, sonra DPO/SimPO/KTO hizalasın. SFT atlayıp doğrudan DPO genelde kararsız, formatı bozuk model üretir. +::: + +## Parametre-verimli yöntemler + +Yukarıdaki tüm trainer'lar commodity GPU'lara sığması için parametre-verimli yöntemlerle birleştirilebilir: + +- **LoRA / QLoRA / DoRA / PiSSA / rsLoRA** — tüm ağırlıklar yerine düşük-rank adapter'ları eğitir. ~%1 eğitilebilir parametre, ~%10 VRAM, çoğu görevde karşılaştırılabilir kalite. +- **GaLore** — gradient projeksiyonu, LoRA seviyesi bellekte full-parametre eğitim. + +Bkz. [LoRA, QLoRA, DoRA](#/training/lora) ve [GaLore](#/training/galore). + +## Dağıtık eğitim + +Modeliniz tek bir GPU belleğinden büyük olduğunda ForgeLM şunları destekler: + +- **DeepSpeed ZeRO-2 / ZeRO-3** — optimizer state / gradient / parametreleri GPU'lar arası shard. +- **FSDP** — PyTorch-yerli tam-shardlı veri paralelizmi. +- **Unsloth** — desteklenen mimarilerde 2-5× daha hızlı backend (sadece tek GPU). + +Bkz. [Dağıtık Eğitim](#/training/distributed). + +## Sıraki adım + +- [Trainer Seçimi](#/concepts/choosing-trainer) — SFT/DPO/SimPO/KTO/ORPO/GRPO arasında karar ağacı. +- [SFT](#/training/sft) — neredeyse her proje burada başlar. +- [Dataset Formatları](#/concepts/data-formats) — her trainer JSONL'da neyi bekler. diff --git a/docs/usermanuals/tr/concepts/choosing-trainer.md b/docs/usermanuals/tr/concepts/choosing-trainer.md new file mode 100644 index 00000000..16715ee0 --- /dev/null +++ b/docs/usermanuals/tr/concepts/choosing-trainer.md @@ -0,0 +1,101 @@ +--- +title: Trainer Seçimi +description: SFT, DPO, SimPO, KTO, ORPO ve GRPO arasında seçim için karar ağacı. +--- + +# Trainer Seçimi + +Bir fine-tuning projesindeki en büyük tek karar hangi trainer'ı kullanacağınızdır — ve doğru cevap neredeyse her zaman tercihleriniz değil verilerinizdir. + +## Karar ağacı + +```mermaid +flowchart TD + Start{Ne tür
veriniz var?} + Q1[Sadece prompt-completion
çiftleri] + Q2[Chosen vs rejected
çiftleri] + Q3[Tek yanıt için
ikili thumbs up/down] + Q4[Hem çiftler
hem tercihler] + Q5[Reward fonksiyonu veya
doğrulanabilir kontrol] + + Start --> Q1 + Start --> Q2 + Start --> Q3 + Start --> Q4 + Start --> Q5 + + Q1 --> SFT([SFT]) + Q2 --> Q2a{VRAM dar veya
referans yok mu?} + Q2a -->|Evet| SimPO([SimPO]) + Q2a -->|Hayır| DPO([DPO]) + Q3 --> KTO([KTO]) + Q4 --> Q4a{Tek aşama
istiyor musunuz?} + Q4a -->|Evet| ORPO([ORPO]) + Q4a -->|Hayır| Combo[SFT sonra DPO] + Q5 --> GRPO([GRPO]) + + classDef start fill:#1c2030,stroke:#f97316,color:#e6e7ec + classDef question fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + classDef result fill:#1c2030,stroke:#22c55e,color:#e6e7ec + class Start,Q2a,Q4a start + class Q1,Q2,Q3,Q4,Q5 question + class SFT,DPO,SimPO,KTO,ORPO,GRPO,Combo result +``` + +## Veriden ne kadarına bakmalı + +| Veri şekli | Önerilen trainer | +|---|---| +| Sadece `{prompt, completion}` satırları | [SFT](#/training/sft) | +| `{prompt, chosen, rejected}` satırları | [DPO](#/training/dpo) (VRAM dar ise [SimPO](#/training/simpo)) | +| `{prompt, response, label: bool}` satırları | [KTO](#/training/kto) | +| SFT ve tercih satırlarının karışımı | [SFT](#/training/sft) → [DPO](#/training/dpo) sıralı, veya tek aşama için [ORPO](#/training/orpo) | +| Programatik reward (math grader, kod testi) | [GRPO](#/training/grpo) | + +## Compute hesabı + +Veriden trainer seçtikten sonra VRAM'e sığacağını teyit edin: + +| Trainer | VRAM (aynı model + max_length ile SFT'e göre) | +|---|---| +| SFT | 1.0× (taban) | +| ORPO | 1.5× | +| SimPO | 1.2× | +| KTO | 1.5× | +| DPO | 2.0× — referans modeli bellekte tutar | +| GRPO | 2-3× — referans + reward bileşenleri de | + +:::tip +QLoRA bu sayıları ~3-4× düşürür. Full precision'da 22 GB isteyen 7B DPO koşusu QLoRA ile ~7 GB'a sığar. Bkz. [LoRA, QLoRA, DoRA](#/training/lora). +::: + +## Sık başlangıç noktaları + +`forgelm quickstart` ile gelen şablonlar; çoğu ekibin ilk koşusu şunlardır: + +| Hedef | Şablon | Trainer dizisi | +|---|---|---| +| Yardımsever + güvenli müşteri destek botu | `customer-support` | SFT → DPO | +| Kod-tamamlama modeli | `code-assistant` | SFT → ORPO | +| PDF'lerinizden alan uzmanı | `byod-domain-expert` | Sadece SFT | +| Matematik akıl yürütme | `math-reasoning` | format-shaping reward'lı GRPO | +| Türkçe medikal Q&A | `medical-qa-tr` | Sadece SFT | + +## Anti-pattern'ler + +:::warn +**"SFT'siz DPO."** Sık yapılan bir hata — base modele direkt DPO. Format ve içerik öğreten SFT olmadan DPO kırılgandır ve sonuç model genelde bozuk format çıkarır. +::: + +:::warn +**"Her şeye GRPO."** GRPO doğrulanabilir doğruluk olan görevler için güçlü (sayısal cevaplı matematik, geçen testli kod). Açık uçlu kalite tercihleri için DPO daha kararlı ve hata ayıklaması kolaydır. +::: + +:::warn +**"Veri 'iyi görünüyor' diye audit'i atlamak."** [Önce verinizi denetleyin](#/data/audit) — sızdıran train/test split'i veya veri setinizdeki PII, "yanlış" trainer seçmekten çok daha olası şekilde koşunuzu mahveder. +::: + +## Bkz. + +- [Alignment Yığını](#/concepts/alignment-overview) — daha geniş bağlam. +- [Dataset Formatları](#/concepts/data-formats) — her trainer'ın beklediği JSONL. diff --git a/docs/usermanuals/tr/concepts/data-formats.md b/docs/usermanuals/tr/concepts/data-formats.md new file mode 100644 index 00000000..b129d6fa --- /dev/null +++ b/docs/usermanuals/tr/concepts/data-formats.md @@ -0,0 +1,142 @@ +--- +title: Dataset Formatları +description: SFT, DPO, SimPO, KTO, ORPO ve GRPO için JSONL formatları — her trainer ne bekler. +--- + +# Dataset Formatları + +Her ForgeLM trainer'ı belirli bir JSONL formatı bekler. ForgeLM dosyanın ilk satırından formatı otomatik algılar; explicit beyan etmenize gerek yok — ama doğru şekli üretmeniz gerekir. + +## Hızlı referans + +| Format | Kullanan | Gerekli alanlar | +|---|---|---| +| `instructions` | SFT | `prompt`, `completion` | +| `messages` | SFT (multi-turn) | `messages: [{role, content}, …]` | +| `preference` | DPO, SimPO, ORPO | `prompt`, `chosen`, `rejected` | +| `binary` | KTO | `prompt`, `response`, `label` | +| `reward` | GRPO | `prompt` (yanıt eğitim sırasında üretilir) | + +## Instructions (tek-tur SFT) + +En basit format — satır başına bir prompt, bir completion. + +```json +{"prompt": "Türkiye'nin başkenti neresi?", "completion": "Ankara."} +{"prompt": "'Hello' kelimesini Türkçeye çevir.", "completion": "Merhaba."} +``` + +Opsiyonel alanlar: +- `system` — konuşmaya prepend edilen system prompt'u. +- `metadata` — keyfi dict; audit log'da korunur, eğitimde kullanılmaz. + +## Messages (multi-turn SFT) + +HuggingFace'in yerli chat formatı. Konuşmalar birden fazla turdaysa kullanın. + +```json +{"messages": [ + {"role": "system", "content": "Sen kibar bir müşteri destek temsilcisisin."}, + {"role": "user", "content": "Aboneliğimi nasıl iptal ederim?"}, + {"role": "assistant", "content": "Ayarlar → Faturalandırma → Aboneliği İptal Et adımlarıyla..."}, + {"role": "user", "content": "Yine ücretlendirilir miyim?"}, + {"role": "assistant", "content": "Hayır. Erişiminiz mevcut faturalama döneminin sonuna kadar devam eder."} +]} +``` + +Roller: `system`, `user`, `assistant`. Tool-call rolleri (`tool`, `function`) chat template tanımladığında desteklenir. + +:::tip +Eğitimdeki chat template modelin tokenizer'ından gelir. ForgeLM `tokenizer.apply_chat_template()` kullanır; Llama 3 chat formatında eğitilen model, Llama 3 chat istemcileri tarafından özel bir şey yapmadan doğru servis edilir. +::: + +## Preference (DPO / SimPO / ORPO) + +Her satır üçlü: prompt, tercih edilen yanıt, reddedilen yanıt. + +```json +{ + "prompt": "Aboneliği nasıl iptal ederim?", + "chosen": "Ayarlar → Faturalandırma → Aboneliği İptal Et. Erişim mevcut dönemin sonuna kadar devam eder.", + "rejected": "Sadece ödemeyi durdurmak yeterli." +} +``` + +Opsiyonel: +- `system` — her iki yanıt için ortak system prompt. +- `prompt_messages` — multi-turn prompt array (nadir; prompt kendisi bir konuşma ise). + +Audit (`forgelm audit`) `chosen == rejected` olan satırları flagler — preference toplama pipeline'larında sık bug. + +## Binary (KTO) + +Tek yanıt + thumbs-up/down. Eşli tercihten daha kolay toplanır. + +```json +{"prompt": "Aboneliği nasıl iptal ederim?", "response": "Sadece ödemeyi durdur.", "label": false} +{"prompt": "Aboneliği nasıl iptal ederim?", "response": "Ayarlar → Faturalandırma...", "label": true} +``` + +Anlamlar: +- `label: true` → istenen yanıt +- `label: false` → istenmeyen yanıt + +KTO her iki sınıftan da örnek bekler — minimum %5-10 azınlık sınıfı kararlı eğitim için. + +## Reward (GRPO) + +GRPO completion'ları toplamaz — eğitim sırasında üretir. Promptları siz verirsiniz, ForgeLM yanıt örnekler, reward fonksiyonunuzla skorlar, policy'i günceller. + +```json +{"prompt": "Çöz: 17 × 23 = ?", "ground_truth": "391"} +{"prompt": "Çöz: 144 ÷ 12 = ?", "ground_truth": "12"} +``` + +`ground_truth` alanı ForgeLM için opaque — reward fonksiyonunuza geçirilir: + +```python +# my_reward.py +def reward(prompt: str, response: str, ground_truth: str) -> float: + answer = extract_number(response) + if answer is None: + return -0.5 + return 1.0 if answer == int(ground_truth) else -1.0 +``` + +Yerleşik format/uzunluk reward'ları için bkz. [GRPO](#/training/grpo). + +## Çoklu veri seti karışımı + +```yaml +datasets: + - path: "data/policies.jsonl" + format: "messages" + weight: 0.7 + - path: "data/general-qa.jsonl" + format: "instructions" + weight: 0.3 +``` + +Ağırlıklar 1.0'a tamamlanır; her batch bu olasılıklara göre örneklenir. + +## Otomatik algılama + +`format:` belirtmezseniz ForgeLM ilk boş olmayan satırı inceler: + +| Satırda olan | Algılanan | +|---|---| +| `messages` array | `messages` | +| `chosen` ve `rejected` | `preference` | +| `response` ve `label` (bool) | `binary` | +| `prompt` ve `completion` | `instructions` | +| Sadece `prompt` | `reward` | + +:::warn +Otomatik algılama dosya başına bir kez. JSONL'iniz formatları karıştırırsa loader yanlış yönlendirir. Ayrı dosyalar kullanın ve her ikisini `datasets:` ile referans verin. +::: + +## Bkz. + +- [Doküman Ingest'i](#/data/ingestion) — PDF/DOCX/EPUB/Markdown'ı bu formatlara dönüştür. +- [Veri Seti Denetimi](#/data/audit) — eğitimden önce çalıştır. +- [Trainer Seçimi](#/concepts/choosing-trainer) — verinizi doğru trainer'a eşleyin. diff --git a/docs/usermanuals/tr/data/audit.md b/docs/usermanuals/tr/data/audit.md new file mode 100644 index 00000000..71e6ea9e --- /dev/null +++ b/docs/usermanuals/tr/data/audit.md @@ -0,0 +1,147 @@ +--- +title: Veri Seti Denetimi +description: PII, sırlar, sızıntı, near-duplicate ve kalite sorunlarını eğitiminizi mahvetmeden yakalayın. +--- + +# Veri Seti Denetimi + +`forgelm audit`, eğitim verinizin CPU-only, streaming ön uçuş kontrolüdür. Modeli safety review'dan geçemeyen, üretimde sırları sızdıran veya test setini ezberleyen bug'ları yakalar. Her eğitim öncesi koşturun. + +```mermaid +flowchart LR + A[JSONL veri] --> B[forgelm audit] + B --> C[PII tarama] + B --> D[Sırlar tarama] + B --> E[Near-dup tarama] + B --> F[Kalite filtresi] + B --> G[Dil tespiti] + B --> H[Split-arası sızıntı] + C & D & E & F & G & H --> I[data_audit_report.json] + classDef io fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef check fill:#161a24,stroke:#f97316,color:#e6e7ec + class A,B,I io + class C,D,E,F,G,H check +``` + +## Hızlı örnek + +```shell +$ forgelm audit data/preferences.jsonl --output ./audit/ +✓ format: preference (12,400 satır, 3 split) +⚠ PII: 12 e-posta, 3 telefon, 1 IBAN (orta seviye, raporu görün) +✓ sırlar: 0 tespit +⚠ near-duplicate çift: 47 (LSH-banded simhash, eşik 3) +✗ chosen-rejected aynı: 12 satır (toplama bug'ı) +✓ dil: %99.2 Türkçe, %0.8 İngilizce +✓ split-arası sızıntı yok + +audit tamamlandı — bkz. ./audit/data_audit_report.json +``` + +Exit kodu ciddiyeti yansıtır: + +| Exit | Anlam | +|---|---| +| `0` | Temiz. Eğitim güvenli. | +| `2` | Uyarı. Raporu inceleyin; eğitim çalışır ama kalite düşebilir. | +| `3` | Hata. Split-arası sızıntı veya başka kritik sorun. Düzelt. | + +## Audit'in kontrol ettikleri + +### PII + +E-posta, telefon, kredi kartı (Luhn doğrulamalı), IBAN ve ulusal kimlik (TR, DE, FR, US-SSN) tespit eder. Bkz. [PII Maskeleme](#/data/pii-masking). + +### Sırlar + +AWS anahtarları, GitHub PAT'ler, Slack token'lar, OpenAI/Google API key'leri, JWT'ler, tam PEM özel anahtar blokları, Azure storage string'leri. Bkz. [Sırların Temizlenmesi](#/data/secrets). + +### Near-duplicate tespiti + +İki algoritma: +- **LSH-banded simhash** (varsayılan) — kesin recall, hızlı, <50K satır için iyi. +- **MinHash LSH** — yaklaşık, milyonlara ölçeklenir. + +Bkz. [Tekrar Tespiti](#/data/deduplication). + +### Kalite filtresi + +Gopher, C4, RefinedWeb araştırmasından heuristik. Düşük alfa, anormal kelime uzunluğu, tekrarlayan satırlar veya kısa paragraflar olan satırları flagler. Muhafazakar — sessizce satır düşürmez. Bkz. [Kalite Filtresi](#/data/quality-filter). + +### Dil tespiti + +Satır başına dominant dili belirlemek için `langdetect`. Bkz. [Dil Tespiti](#/data/language-detection). + +### Split-arası sızıntı + +Train vs validation vs test satırları arasında kesin ve near-duplicate eşleşmeleri karşılaştırır. En pahalı değerlendirme bug'ı. Audit sızdıran split'i onaylamaz. Bkz. [Split-arası Sızıntı](#/data/leakage). + +### Format-özgü kontroller + +**Preference** dataset'leri için ayrıca: +- `chosen == rejected` satırlar (toplama bug'ı) +- `chosen` `rejected`'tan 10× kısa (yanlışlıkla swap) +- Boş `chosen` veya `rejected` + +**Binary** (KTO): +- Aşırı sınıf dengesizliği (>%99/1) +- Boş yanıtlar +- Boolean olmayan label + +## CLI bayrakları + +| Bayrak | Açıklama | +|---|---| +| `--output PATH` | Audit raporu çıktı dizini (varsayılan `./audit/`). | +| `--strict` | Uyarıları hata olarak işle. Herhangi bir flag'te exit 2. | +| `--dedup-algo {simhash,minhash}` | Varsayılan algoritma override. | +| `--dedup-threshold N` | simhash için Hamming eşiği (varsayılan 3). | +| `--skip-pii / --skip-secrets / ...` | Tek tek kontrolleri kapat. | +| `--sample-rate FLOAT` | Rastgele alt-örnek (`0.1` = %10). Çok büyük dataset için. | + +## Rapor içeriği + +`data_audit_report.json` hem insan okuması hem CI entegrasyonu için yapılandırılmış: + +```json +{ + "format": "preference", + "row_count": 12400, + "splits": {"train": 10000, "val": 1200, "test": 1200}, + "pii_summary": {"email": 12, "phone": 3, "iban": 1, "severity": "medium"}, + "secrets_summary": {"total": 0}, + "near_duplicate_pairs": 47, + "cross_split_overlap": 0, + "quality_flags": {...}, + "language_distribution": {"tr": 0.992, "en": 0.008}, + "preference_specific": {"identical_chosen_rejected": 12, ...}, + "verdict": "warnings" +} +``` + +CI entegrasyonları `verdict` ve sayıları parse ederek merge'i kontrol eder: + +```yaml +- name: Audit data + run: forgelm audit data/train.jsonl --strict +``` + +## Sık hatalar + +:::warn +**"Güvenilen" veride audit'i atlamak.** Kendi üretim log'larınız bile sürpriz içerebilir — son API anahtarı rotasyonu telemetry'ye sızar, GDPR-silme isteği dangling ID yaratır. Audit kendi gelecek hatanıza karşı savunma. +::: + +:::warn +**Küçük dataset'te `--sample-rate`.** Sample milyon-satır corpus için anlamlı; <10K satır için hepsini denetle — saniyeler sürer. +::: + +:::tip +**Sürüm başına audit raporu sakla.** `data_audit_report.json`'u dataset versiyonuyla birlikte git'e commit'le. Gelecek audit'ler tarihsel rapora karşı diff alıp "geçen sefer 12 PII flag vardı, şimdi 47 — pipeline'da ne değişti?" cevabı verebilir. +::: + +## Bkz. + +- [PII Maskeleme](#/data/pii-masking), [Sırlar](#/data/secrets), [Tekrar](#/data/deduplication) — tek tek kontroller. +- [Annex IV](#/compliance/annex-iv) — audit raporu compliance artifact'lara akar. +- [Konfigürasyon Referansı](#/reference/configuration) — `compliance.data_audit_artifact`. diff --git a/docs/usermanuals/tr/data/deduplication.md b/docs/usermanuals/tr/data/deduplication.md new file mode 100644 index 00000000..9aecc87a --- /dev/null +++ b/docs/usermanuals/tr/data/deduplication.md @@ -0,0 +1,115 @@ +--- +title: Tekrar Tespiti +description: Eğitim verisinde near-duplicate yakalamak için LSH-banded simhash ve MinHash LSH. +--- + +# Tekrar Tespiti + +Tekrarlar ve near-duplicate'ler eğitim dağılımınızı tekrarlanan şeye doğru şişirir; train/eval split'lerini geçerlerse değerlendirme metriklerinizi anlamsızlaştırır. ForgeLM iki algoritma yayınlar: doğruluk ve küçük-orta corpus için simhash, ölçek için MinHash LSH. + +## Algoritma seçimi + +| Algoritma | Recall | Hız | En iyi | +|---|---|---|---| +| **LSH-banded simhash** (varsayılan) | Hamming eşiği içinde kesin | ~50K satır/s | Corpus < 50K satır | +| **MinHash LSH** | Yaklaşık (gerçek tekrarların >%95'i) | ~500K satır/s | Corpus > 50K satır | + +ForgeLM satır sayısına göre otomatik seçer — küçük için simhash, büyük için MinHash — ama `--dedup-algo` ile override edebilirsiniz. + +## Hızlı örnek + +```shell +$ forgelm audit data/train.jsonl --dedup-threshold 3 +⚠ near-duplicate çift: 47 (LSH-banded simhash, eşik 3) + +$ jq '.near_duplicates[]' audit/data_audit_report.json | head +{"row_a": 1240, "row_b": 4521, "hamming": 1, "similarity": 0.984} +{"row_a": 9012, "row_b": 9013, "hamming": 0, "similarity": 1.0} +``` + +`hamming: 0` *kesin* tekrarlardır (aynı simhash); yüksek değerler giderek daha az benzer. + +## Eşik ayarlama + +`--dedup-threshold` 64-bit simhash üzerinde Hamming mesafesidir. Varsayılanlar: + +| Eşik | Yakalanan | False-positive oranı | +|---|---|---| +| 0 | Sadece kesin tekrarlar | ~0% | +| 1-2 | Trivial-edit tekrarları ("Merhaba!" vs "Merhaba.") | <1% | +| **3** (varsayılan) | Yapı paylaşan parafraz'lar | 1-2% | +| 5+ | Gevşek parafraz'lar; yüksek false-positive | 5-15% | + +Çoğu ekip 3'te kalır. + +## Near-dup'ın exact-match'in yakalamadığı + +```text +Satır A: "Müşteri desteğine hoş geldiniz. Size nasıl yardımcı olabilirim?" +Satır B: "Müşteri desteğine hoş geldiniz — size nasıl yardımcı olabilirim?" +``` + +Exact-match bunları kaçırır (farklı noktalama). Eşik 3 ile simhash yakalar. + +```text +Satır A: "CV'nizi ali@example.com'a gönderin" +Satır B: "CV'nizi ali@example.com'a gönderin veya bizi arayın" +``` + +Eşik 3 bunları da yakalar (aynı ilk yarı, hafif uzatma). + +## Split-arası farkındalık + +Audit, near-dup tespitini hem split *içinde* hem *arası* koşturur. Split-arası tekrarlar yüksek-öncelikli bug — benchmark puanlarınızı güvenilmez kılar. Audit'in `cross_split_overlap` alanı kaç train satırının validation veya test'te near-duplicate'i olduğunu raporlar. Bkz. [Split-arası Sızıntı](#/data/leakage). + +## Ölçek için MinHash LSH + +50K satır üzeri corpus için MinHash'a geçin: + +```shell +$ forgelm audit data/large.jsonl --dedup-algo minhash --num-perm 256 +✓ near-duplicate çift: 1,247 (MinHash LSH, 256 permutasyon, eşik 0.85) +``` + +MinHash büyük hız için küçük doğruluk ödünleşir — milyon-satır dataset'lerde simhash'tan 10× hızlı koşarken tipik recall gerçek tekrarların >%95'i. + +| MinHash bayrak | Açıklama | +|---|---| +| `--num-perm` | Hash permutasyon sayısı (varsayılan 128). Daha çok = daha doğru, daha çok bellek. | +| `--minhash-threshold` | Jaccard benzerlik eşiği (varsayılan 0.85). | +| `--minhash-bands` | LSH banding parametresi (varsayılan eşikten otomatik türetilir). | + +## Streaming davranış + +İki algoritma da streaming — tüm dataset'i belleğe yüklemez. 10M-satır corpus laptop CPU'sunda birkaç dakikada deduplike edilir. + +## Tekrarları kaldırma + +`forgelm audit` tekrarları *tespit eder*; varsayılan kaldırmaz (veri modifikasyonu bilinçli). Deduplike etmek için: + +```shell +$ forgelm audit data/train.jsonl --remove-duplicates --output-clean data/train.dedup.jsonl +✓ 47 near-duplicate satır kaldırıldı; data/train.dedup.jsonl yazıldı (12,353 satır) +``` + +Tekrarlar tek split içindeyken ForgeLM ilk tekrarı tutar. Split arasında varsayılan train tarafını tutar ve validation/test'ten kaldırır (konfigüre edilebilir). + +## Sık hatalar + +:::warn +**Eşik çok agresif.** Simhash'ta 5+ Hamming eşiği meşru farklı örnekleri tekrar olarak flagler. Spesifik veriniz üzerinde false-positive oranı ölçmediyseniz 3'te kalın. +::: + +:::warn +**MinHash permutasyonu çok düşük.** `--num-perm 64` bellek tasarrufu sağlar ama recall ~%85'e düşer. Üretim kullanımı için 128'in üstünde kalın. +::: + +:::tip +**Train/val/test'i manuel ayırmadan ÖNCE dedup koşturun.** Split'leriniz yukarıdan üretildi ve sızıntı varsa deduplikasyonla düzeltemezsiniz; yeniden split'lemeniz gerekir. Birleşik dataset üzerinde audit, split öncesi bunu yakalar. +::: + +## Bkz. + +- [Veri Seti Denetimi](#/data/audit) — standart audit'in parçası olarak dedup koşturur. +- [Split-arası Sızıntı](#/data/leakage) — en yüksek öncelikli deduplikasyon kaygısı. +- [Kalite Filtresi](#/data/quality-filter) — düşük-kaliteli satırları yakalayan kardeş özellik. diff --git a/docs/usermanuals/tr/data/ingestion.md b/docs/usermanuals/tr/data/ingestion.md new file mode 100644 index 00000000..42139564 --- /dev/null +++ b/docs/usermanuals/tr/data/ingestion.md @@ -0,0 +1,122 @@ +--- +title: Doküman Ingest'i +description: PDF, DOCX, EPUB, TXT ve Markdown'ı tek komutla SFT-hazır JSONL'a dönüştürün. +--- + +# Doküman Ingest'i + +Çoğu fine-tuning veri seti JSONL olarak başlamaz — PDF'ler, sözleşmeler, EPUB'lar veya dağınık Markdown notları olarak başlar. `forgelm ingest` girdi dizininizi gezer, metni format-bilinçli şekilde çıkarır ve SFT-hazır JSONL üretir. + +```mermaid +flowchart LR + A[Girdi dizini
PDF/DOCX/EPUB/MD] --> B[Format algıla] + B --> C[Metin çıkar
yapıyı koru] + C --> D[Token bazlı veya
Markdown bazlı parçala] + D --> E[Maskeleme uygula
PII + sırlar] + E --> F[JSONL çıktı] + classDef io fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef step fill:#161a24,stroke:#f97316,color:#e6e7ec + class A,F io + class B,C,D,E step +``` + +## Hızlı örnek + +```shell +$ forgelm ingest ./policies/ \ + --recursive \ + --strategy markdown \ + --max-tokens 1024 \ + --pii-mask --secrets-mask \ + --output data/policies.jsonl +✓ 47 dosya tarandı (12 PDF, 8 DOCX, 27 MD) +✓ 12,240 chunk çıkarıldı (ortalama 743 token) +✓ 18 PII eşleşmesi maskelendi, 0 sır +✓ data/policies.jsonl yazıldı (8.2 MB) +``` + +## Desteklenen formatlar + +| Format | Çıkarıcı | Notlar | +|---|---|---| +| **PDF** | `pypdf` | Header/footer dedup, tablo çıkarma (best-effort). | +| **DOCX** | `python-docx` | Tablolar Markdown tablo olarak; başlık hiyerarşisini korur. | +| **EPUB** | `ebooklib` | Navigasyon/içindekileri çıkarır; bölüm yapısını korur. | +| **TXT** | yerleşik | Tek doküman olarak işlenir; `--max-tokens` ile parçalanır. | +| **Markdown** | yerleşik | Markdown-bilen splitter başlık hiyerarşisine saygı duyar. | + +Ingestion extra'larını kurun: `pip install 'forgelm[ingestion]'`. Bkz. [Kurulum](#/getting-started/installation). + +## Parçalama stratejileri + +| Strateji | Davranış | En iyi | +|---|---|---| +| `tokens` | Chunk başına `--max-tokens` sınırı; cümle sınırlarında bölmeye çalışır. | Düz metin, karışık içerik. | +| `markdown` | Markdown başlıklarına (h1/h2/h3) göre böler, hiyerarşiye saygı duyar. | Dokümantasyon, yapılandırılmış corpus. | +| `paragraph` | Paragraf başına bir chunk (veya sığacak şekilde birleştirilmiş paragraflar). | Kitaplar, prose. | +| `sentence` | Cümle başına bir chunk (nadir; çok ince taneli veri için). | NLI görevleri, kısa Q&A. | + +Çoğu ekip dokümantasyon için `markdown`, geri kalan her şey için `tokens` seçer. + +## Çıktı formatları + +Varsayılan olarak `forgelm ingest` sentetik prompt'larla `instructions` formatı üretir: + +```json +{"prompt": "Şu pasajı özetle.", "completion": "Politikanın 4.2 bölümü...", "metadata": {"source": "policy.pdf", "chunk": 17}} +``` + +Domain-uzmanı SFT için genelde `--format raw` istersiniz; bu chunk'ı olduğu gibi çıkarır ve prompt üretimini sonraya bırakır (veya sürdürülen ön eğitim için kullanır): + +```json +{"text": "Bölüm 4.2: Tüm ödeme işlemleri PCI-DSS standartlarına uymalıdır...", "metadata": {"source": "policy.pdf", "chunk": 17}} +``` + +Q&A datasetleri için prompt-üreten LLM ile `--format qa`: + +```yaml +ingestion: + format: "qa" + qa_generator: + model: "openai:gpt-4o-mini" + prompts_per_chunk: 3 +``` + +## CLI bayrakları + +| Bayrak | Açıklama | +|---|---| +| `--recursive` | Alt dizinlere yürü. | +| `--strategy {tokens,markdown,paragraph,sentence}` | Parçalama stratejisi. | +| `--max-tokens N` | Chunk başına token sınırı (varsayılan 1024). | +| `--overlap N` | Chunk'lar arası kayar-pencere örtüşmesi (varsayılan 0). | +| `--pii-mask` | E-posta, telefon, ID, IBAN'ı yazmadan önce maskele. Bkz. [PII Maskeleme](#/data/pii-masking). | +| `--secrets-mask` | AWS anahtarları, GitHub PAT'ler, JWT'leri vb. redakte et. Bkz. [Sırlar](#/data/secrets). | +| `--language LANG` | Bir dili zorla (varsayılan: chunk başına otomatik algıla). | +| `--include "*.pdf,*.md"` | Dahil edilecek glob pattern'leri. | +| `--exclude "drafts/*"` | Hariç tutulacak glob pattern'leri. | +| `--output PATH` | Çıktı dosyası (`.jsonl`). | + +## Sık hatalar + +:::warn +**`--pii-mask`'i unutmak.** Varsayılan *maskelememe*; "verinizi sessizce değiştirmeyiz" prensibinden. Gerçek corpus için açıkça etkinleştirin. Audit aşaması ([Veri Seti Denetimi](#/data/audit)) PII'yi her halükarda flagler ama ingest'te maskelemek daha iyidir. +::: + +:::warn +**Saf-resim PDF'ler.** ForgeLM OCR yayınlamıyor. PDF'leriniz taranmış görüntüyse önce Tesseract veya ticari bir OCR'dan geçirin. +::: + +:::warn +**`--max-tokens`'i modelin context'inden büyük yapmak.** `model.max_length`'ten uzun chunk'lar eğitim zamanında kuyruktan kesilir. `--max-tokens`'i eğitim context'iyle eşleştirin. +::: + +:::tip +**Ingest'ten sonra her zaman audit yapın.** Temiz ingest temiz dataset anlamına gelmez. Split-arası sızıntı, near-duplicate ve maskelemenin kaçırdığı PII için `forgelm audit data/output.jsonl` koşturun. +::: + +## Bkz. + +- [Veri Seti Denetimi](#/data/audit) — ingest'ten sonraki adım. +- [PII Maskeleme](#/data/pii-masking) — maskelemenin nasıl çalıştığı. +- [Dataset Formatları](#/concepts/data-formats) — her çıktı formatı. diff --git a/docs/usermanuals/tr/data/language-detection.md b/docs/usermanuals/tr/data/language-detection.md new file mode 100644 index 00000000..49679f3c --- /dev/null +++ b/docs/usermanuals/tr/data/language-detection.md @@ -0,0 +1,81 @@ +--- +title: Dil Tespiti +description: Satır başı dil tanımlama — "Türkçe olmalıyken %12'si İngilizce kaydı" bug'ını yakalayın. +--- + +# Dil Tespiti + +Gerçek-dünya dataset'leri nominal olarak tek dilde olur ama kazara başkalarını içerebilir — Türkçe corpus'a yapıştırılmış İngilizce dokümantasyon, İspanyolca dataset'te Fransızca hukuk boilerplate. ForgeLM satır başı dili tespit eder ve audit zamanında dağılımı raporlar. + +## Hızlı örnek + +```shell +$ forgelm audit data/medical-tr.jsonl +✓ dil: %99.2 tr, %0.5 en, %0.3 diğer + 12 satır 'en' (muhtemelen kazara) + 5 satır 'mixed' (her iki dili içeren) +``` + +Audit raporu satır başı dili ayrıştırır ve aykırı satırların indislerini listeler: + +```shell +$ jq '.language_outliers[:3]' audit/data_audit_report.json +[ + {"row": 1240, "detected": "en", "expected": "tr", "snippet": "Lorem ipsum dolor..."}, + {"row": 4521, "detected": "en", "expected": "tr", "snippet": "Patient should call..."}, + {"row": 9012, "detected": "mixed", "expected": "tr", "snippet": "Hasta günde 3 kez two..."} +] +``` + +## Detector + +`langdetect` kullanır (Google CLD2'nin saf-Python port'u). 55+ dili kutudan çıktığı gibi destekler. Performans: satır başı ~1ms, GPU yok. + +Çok kısa satırlarda (<50 karakter) dil tespiti güvenilmez olur — ForgeLM bunları tahmin etmek yerine `unknown` olarak işaretler. + +## Konfigürasyon + +```yaml +audit: + language_detection: + enabled: true + expected: "tr" # açık beklenen dil + min_chars: 50 # bundan kısa satırlar 'unknown' + mixed_threshold: 0.3 # ikinci-dil güveni > %30 ise 'mixed' işaretle +``` + +`expected` ayarlamazsanız audit dağılımı aykırı flag'lemeden raporlar — gerçekten çok dilli dataset'ler için faydalı. + +## Dil dağılım raporu + +```json +{ + "language_distribution": { + "tr": 0.992, + "en": 0.005, + "ar": 0.001, + "unknown": 0.002 + }, + "language_outliers": 17, + "expected": "tr" +} +``` + +## Sık hatalar + +:::warn +**Çıkarılmış PDF metninde dil tespiti.** PDF çıkarımı bazen aksi takdirde-Türkçe içerikte İngilizce boilerplate ("Confidential", "Page 1 of N", "© 2026 Company") koşuları korur ve tespiti şaşırtır. Bunları ingest'te ön-filtreleyin. +::: + +:::warn +**`min_chars`'i çok düşük ayarlamak.** Kısa satırlar gürültülü tespit üretir. 50'nin üstünde kalın; kalite raporları için 100 daha güvenli. +::: + +:::tip +**Çok dilli dataset'ler.** Dataset'iniz bilinçli çok dilli ise (çeviri çiftleri, çok dilli chat) `expected` ayarlamayın — audit sadece dağılımı raporlasın ve tek doküman içinde karışan satırları flaglesin. +::: + +## Bkz. + +- [Veri Seti Denetimi](#/data/audit) — dil tespitini standart audit'in parçası olarak koşturur. +- [Doküman Ingest'i](#/data/ingestion) — ingest zamanında zorla dil için `--language` bayrağı. diff --git a/docs/usermanuals/tr/data/leakage.md b/docs/usermanuals/tr/data/leakage.md new file mode 100644 index 00000000..87c2be54 --- /dev/null +++ b/docs/usermanuals/tr/data/leakage.md @@ -0,0 +1,121 @@ +--- +title: Split-Arası Sızıntı +description: Train satırlarının validation veya test'te de göründüğünü tespit edin — en pahalı değerlendirme bug'ı. +--- + +# Split-Arası Sızıntı + +Validation veya test'te de görünen train satırları değerlendirme metriklerinizi yanıltıcı şekilde şişirir. Model test cevabını "biliyor" çünkü eğitim sırasında gördü. Raporlanan puanlar iyi görünür; üretim performansı hayal kırıklığı yaratır. + +ForgeLM'in split-arası sızıntı kontrolü tek başına en önemli audit adımıdır. `forgelm audit` her çağrısında koşar ve sızdıran split'i onaylamayı reddeder. + +## Sızıntı nasıl olur + +Olağan suçlular: + +1. **Gruplama olmadan rastgele karıştırma.** Satır başı rastgele bölmek tekrar satırları her iki tarafa da koyar. +2. **Bölme öncesi augmentasyon.** Mevcut satırlardan parafraz üretmek, sonra bölmek — orijinal ve parafraz farklı taraflarda biter. +3. **Aynı içeriğin birden çok kaynağı.** Eğitim corpus'unuzdaki bir FAQ ve eval setinizdeki aynı FAQ, ayrı ingest edilmiş. +4. **Web crawl'lar benchmark'larla örtüşür.** Eğitim verisi web'i taradı; benchmark yayıncısı da test setini web'e koydu. + +## Kontrol ne yapar + +```mermaid +flowchart LR + Train[train.jsonl] --> H[Tüm satırları hashle] + Val[val.jsonl] --> H + Test[test.jsonl] --> H + H --> E[Kesin-eşleşme indeksi] + H --> N[Near-dup simhash] + E --> R[Split-arası örtüşme raporu] + N --> R + classDef io fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef step fill:#161a24,stroke:#f97316,color:#e6e7ec + classDef out fill:#1c2030,stroke:#22c55e,color:#e6e7ec + class Train,Val,Test io + class H,E,N step + class R out +``` + +Her train satırı için ForgeLM kontrol eder: +- Val/test'te **kesin eşleşme** (önemli her alan: `prompt`, `chosen`, `response` vb.). +- Val/test'te **near-duplicate** (Hamming eşiği 3 simhash). + +Herhangi bir eşleşme raporlanır. Sızıntı oranı konfigüre eşiği geçerse audit sıfır olmayan exit verir. + +## Hızlı örnek + +```shell +$ forgelm audit data/ # train.jsonl + val.jsonl + test.jsonl'ı denetler +✗ split-arası örtüşme tespit edildi: + train ↔ val: 47 kesin, 12 near-dup + train ↔ test: 23 kesin, 5 near-dup + val ↔ test: 0 + +Audit bu split'leri onaylamayı reddeder. İndisler için `--show-leakage`. + +exit kodu: 3 +``` + +```shell +$ forgelm audit data/ --show-leakage +{train: 1240, val: 312, type: "exact", text: "Aboneliği nasıl iptal..."} +{train: 4521, val: 890, type: "near-dup", hamming: 2, ...} +``` + +## Nasıl düzeltirsiniz + +1. **Veriyi yeniden bölün**, bu sefer kaynak seviyesinde gruplayarak (parafraz'ları bölmeyin, dokümanları gruplayın). Splitter'ınızda `--group-by` bayrağı kullanın. +2. **Yeniden çıkarma** sızıntı tekrar ingest'ten geliyorsa (aynı FAQ iki kez ingest edilmiş). +3. **Kaldırma** küçük split'ten sızdıran satırları (audit'in `--remove-cross-split-overlap`'i bunu yapar — ama buna güvenmeden önce düşünün). + +```shell +$ forgelm audit data/ --remove-cross-split-overlap=val \ + --output-clean data/clean/ +✓ val'den 47 split-arası satır kaldırıldı (train tarafı korundu) +``` + +## Konfigürasyon + +```yaml +audit: + leakage_check: + enabled: true + threshold: 0 # sıfır tolerans — herhangi sızıntıda audit fail + near_dup_hamming: 3 # eşleşme eşiği + fields_to_check: ["prompt", "chosen", "response"] + fail_severity: "error" # `error` eğitimi engeller, `warn` sadece loglar +``` + +Çoğu ekip varsayılanı kullanır — sıfır tolerans. Bir miktar sızıntının kaçınılmaz olduğu çok büyük dataset'iniz varsa `threshold`'ı küçük bir orana yükseltin (ör. 0.001) ama nedenini belgeleyin. + +## "Near-dup" neden önemli + +Kesin-eşleşme sızıntı modern pipeline'larda nadirdir; çünkü herkes deduplike eder. Ama near-dup sızıntı sessiz katildir: + +```text +Train: "Aboneliği nasıl iptal ederim?" +Test: "Aboneliği nasıl iptal ederim" +``` + +Bir karakter farklı — kesin-eşleşme bunu kaçırır; model her halükarda eğitim zamanında bunları aynı sayar. Near-dup yakalar. + +## Sık hatalar + +:::warn +**Augmentasyondan sonra bölme.** Eğitim verisinden parafraz üretip sonra rastgele bölerseniz parafraz diğer tarafta biter. Her zaman augmentasyondan *önce* bölün. +::: + +:::warn +**Yukarıdan gelen split'lere güvenmek.** Dataset'iniz önceden tanımlanmış train/val/test split'leriyle yayınlandıysa, onları denetleyin. Kamuya açık dataset'lerin yıllardır yayılan bilinen sızıntıları olabilir. +::: + +:::danger +**"Bugün üretime girmek için" sızıntı kontrolünü atlatmak.** Sızdıran koşunun fiyatı, iyi benchmark numaraları raporlamak, deploy etmek ve üretim performansının çok daha kötü olduğunu keşfetmektir. Güven kaybı, gecikmenin maliyetinden fazlasına mal olur. +::: + +## Bkz. + +- [Veri Seti Denetimi](#/data/audit) — sızıntı kontrolü varsayılan koşar. +- [Tekrar Tespiti](#/data/deduplication) — aynı simhash backend. +- [Annex IV](#/compliance/annex-iv) — sızıntı raporu compliance paketinin parçası. diff --git a/docs/usermanuals/tr/data/pii-masking.md b/docs/usermanuals/tr/data/pii-masking.md new file mode 100644 index 00000000..fe1330e1 --- /dev/null +++ b/docs/usermanuals/tr/data/pii-masking.md @@ -0,0 +1,139 @@ +--- +title: PII Maskeleme +description: E-posta, telefon, kredi kartı, IBAN ve ulusal kimlikleri ingest sırasında tespit edip redakte edin. +--- + +# PII Maskeleme + +Eğitim setinizdeki kişisel veri hem regülatif tehlikedir (GDPR Md. 5(1)(c) — veri minimizasyonu) hem operasyonel tehlikedir (model ezberler ve geri verir). ForgeLM'in PII maskeleyicisi dokuz kategori PII'yi tespit eder ve ingest zamanında, satırlar JSONL'a düşmeden redakte eder. + +## Tespit edilenler + +| Kategori | Örnekler | Nasıl | +|---|---|---| +| **E-posta** | `ali@example.com` | RFC 5321-uyumlu regex | +| **Telefon** | `+90 532 123 45 67`, `(555) 123-4567` | E.164-uyumlu pattern + locale varyantları | +| **Kredi kartı** | `4111-1111-1111-1111` | Visa/MC/Amex/Discover pattern + Luhn (görünür benzerlerde false-positive yok) | +| **IBAN** | `TR12 0006 4000 0011 2345 6789 01` | Ülke-bilinçli checksum | +| **Ulusal ID — Türkiye** | 11 haneli TC kimlik | Modulo-10 + modulo-11 checksum | +| **Ulusal ID — Almanya** | Steuer-ID | Format + checksum | +| **Ulusal ID — Fransa** | NIR (sosyal güvenlik) | Format + key validation | +| **US SSN** | `123-45-6789` | Format + reserved-block dışlama | +| **IPv4 / IPv6** | `192.168.1.1`, `2001:db8::1` | Standart regex (varsayılan kapalı; opt-in) | + +## Hızlı örnek + +Ingest zamanında: + +```shell +$ forgelm ingest ./policies/ \ + --recursive --strategy markdown \ + --pii-mask \ + --output data/policies.jsonl +✓ 12,240 chunk üzerinde 18 PII eşleşmesi maskelendi +``` + +Ingest sonrası her eşleşme etiketli placeholder'la değiştirilir: + +```text +Önce: "CV'nizi ali@example.com'a gönderin veya +90 532 555 7890'ı arayın." +Sonra: "CV'nizi [EMAIL_REDACTED]'a gönderin veya [PHONE_REDACTED]'ı arayın." +``` + +Placeholder dataset boyunca tutarlı; model "şu slot'a *bir* e-posta gelir" öğrenebilir — sadece spesifik olanı değil. + +## Yayınlanan etiketler + +| Etiket | Yerine geçer | +|---|---| +| `[EMAIL_REDACTED]` | E-posta adresleri | +| `[PHONE_REDACTED]` | Telefon numaraları | +| `[CREDITCARD_REDACTED]` | Kredi kartları (Luhn doğrulamalı) | +| `[IBAN_REDACTED]` | IBAN'lar | +| `[ID_TR_REDACTED]` | TC kimlik numaraları | +| `[ID_DE_REDACTED]` | Steuer-ID'ler | +| `[ID_FR_REDACTED]` | NIR numaraları | +| `[SSN_REDACTED]` | US SSN'ler | +| `[IP_REDACTED]` | IP adresleri | + +## Tasarım gereği muhafazakar + +PII regex'leri bilinçli olarak **düşük false-positive oran** için ayarlanır. Sınırda eşleşmeyi atlamayı (false negative) prose'unuzdaki PII olmayan string'i redakte etmeye (false positive) tercih eder. Sebepler: + +1. False positive sessizce verinizi bozar — gerçek kelimeleri `[EMAIL_REDACTED]` ile değiştirmek örnekleri mahveder. +2. Audit aşaması maskelemenin kaçırdığını yakalar; satır başına düzeltme veya düşürme kararı sizde. +3. Agresif regex'ler gerçek-dünya ML pipeline kesintilerine yol açtı (Phase 11.5 olayı `docs/standards/regex.md`'de belgelenmiştir). + +Daha katı tespit gerekirse — örneğin yüksek-stake bir hukuk corpus'u — maskeleyiciyi manuel inceleme adımıyla birleştirin. Regex'leri zorlamayın. + +## Sadece-audit modu + +Modifiye etmeden tespit için: + +```shell +$ forgelm audit data/policies.jsonl +⚠ PII: 18 e-posta, 4 telefon, 2 IBAN (orta seviye) +``` + +Audit raporu satır indisleri ve offset'leri listeler; spesifik vakaları inceleyebilirsiniz. + +## Locale'ler + +| Locale | Telefon | Ulusal ID | Notlar | +|---|---|---|---| +| TR (varsayılan) | E.164 + Türkiye formatları | TC kimlik | En çok ayarlanan. | +| DE | E.164 + Almanya formatları | Steuer-ID | | +| FR | E.164 + Fransa formatları | NIR | | +| US | E.164 + (xxx) xxx-xxxx | Reserved-block dışlamalı SSN | | +| Global | Sadece E.164 | yok | Bilinmeyen locale fallback. | + +Locale'i ingest'te ayarlayın: + +```shell +$ forgelm ingest ./docs/ --pii-mask --pii-locale de +``` + +Veya YAML'da: + +```yaml +ingestion: + pii_mask: + enabled: true + locale: "de" + categories: ["email", "phone", "iban", "id_de"] + skip: ["ip"] # IP'leri redakte etme +``` + +## Programatik API + +Ingest dışı PII tespiti gerektiren pipeline'lar için: + +```python +from forgelm.data_audit import detect_pii, mask_pii + +text = "E-posta: ali@example.com, Tel: +90 532 555 7890" +hits = detect_pii(text, locale="tr") +print(hits) +# [{'category': 'email', 'span': (8, 23), 'value': 'ali@example.com'}, +# {'category': 'phone', 'span': (29, 45), 'value': '+90 532 555 7890'}] + +masked = mask_pii(text, locale="tr") +print(masked) +# E-posta: [EMAIL_REDACTED], Tel: [PHONE_REDACTED] +``` + +## Sık hatalar + +:::warn +**Compliance sertifikasyonu için PII maskelemeye güvenmek.** PII maskeleme savunma derinliği önlemidir, sertifikasyon değil. Yüksek-riskli corpus için (hukuk, tıp), maskelemeyi manuel inceleme ile birleştirin. ForgeLM PII'yi modifiye etmeden flagleyen `audit` modu yayınlar; inceleyebilirsiniz. +::: + +:::warn +**Test etmeden özel PII kategorileri.** Repo'nun `regex.md` standardı yeni pattern eklemek için 8 sıkı kural belgeler. Test checklist'ini atlamak false-positive bug'ların yayınlanmasının yolu. +::: + +## Bkz. + +- [Veri Seti Denetimi](#/data/audit) — modifiye etmeden PII tespiti koşturur. +- [Sırların Temizlenmesi](#/data/secrets) — kimlik bilgileri için kardeş özellik. +- [GDPR / KVKK](#/compliance/gdpr) — regülatif bağlam. diff --git a/docs/usermanuals/tr/data/quality-filter.md b/docs/usermanuals/tr/data/quality-filter.md new file mode 100644 index 00000000..9c3d3f66 --- /dev/null +++ b/docs/usermanuals/tr/data/quality-filter.md @@ -0,0 +1,98 @@ +--- +title: Kalite Filtresi +description: Düşük-kaliteli eğitim satırlarını yakalamak için Gopher, C4 ve RefinedWeb'den heuristikler. +--- + +# Kalite Filtresi + +Eğitim verinizdeki tüm satırlar eşit faydalı değildir. Boilerplate, OCR hataları, tekrarlanan satırlar ve saf-simge gürültüsü sinyali sulandırır. ForgeLM'in kalite filtresi Gopher, C4 ve RefinedWeb araştırma soylarından heuristikler uygular — muhafazakar şekilde, sessizce satır düşürmeden. + +## Flaglenenler + +| Heuristik | Yakaladığı | +|---|---| +| **Düşük alfa oranı** | `<%55` alfabetik karakter — genelde kod dump'ları, log spam veya saf simgeler. | +| **Anormal ortalama kelime uzunluğu** | Ortalama `<3` veya `>10` karakterli kelimeler — sıklıkla OCR çöpü veya sadece-URL satırlar. | +| **Tekrarlayan satır oranı** | Satırların `>%30`'u tekrarlanmış — boilerplate veya çıkarma artifact'ı. | +| **Kısa içerik** | Konfigüre minimum altında toplam uzunluk — sıklıkla çıkarma sonrası boş. | +| **Sadece-bullet satırlar** | Satırların `>%90`'ı bullet işaretiyle başlıyor — genelde çıkarılmış nav menüleri. | +| **Simge yoğunluğu** | Aşırı `_-=#*` yoğunluğu — genelde render edilmiş tablolar veya pre-format metin. | + +Her satır audit raporunda `quality_flags` listesi alır. Filtre asla otomatik düşürmez; karar size ait. + +## Hızlı örnek + +```shell +$ forgelm audit data/ingested.jsonl +⚠ kalite flag'leri: + short_response: 24 + repeated_lines: 12 + abnormal_word_length: 6 + bullet_only: 3 +``` + +Flaglenen satırları düşürmek için: + +```shell +$ forgelm audit data/ingested.jsonl --drop-quality-flags --output-clean data/clean.jsonl +✓ 45 satır düşürüldü; data/clean.jsonl yazıldı (12,355 satır) +``` + +## Eşik ayarlama + +```yaml +audit: + quality_filter: + enabled: true + min_alpha_ratio: 0.55 # varsayılan 0.55 + min_mean_word_length: 3 # varsayılan 3 + max_mean_word_length: 10 # varsayılan 10 + max_repeated_line_ratio: 0.30 # varsayılan 0.30 + min_content_length: 50 # varsayılan 50 karakter + max_bullet_ratio: 0.90 # varsayılan 0.90 +``` + +Birini meşru ihlal eden corpus'lar (ör. kod-ağırlıklı dataset'ler alfa oranını ihlal eder) için filtre tamamı yerine spesifik kontrolü kapatın: + +```yaml +audit: + quality_filter: + enabled: true + skip: ["min_alpha_ratio"] # kod, matematik, log dataset'leri +``` + +## Tasarım gereği muhafazakar + +Eşikler *flag, düşürme* için ayarlandı. Sebepler: + +1. Domain uyumsuzluğu — web crawl'lara ayarlanmış kalite filtresi medikal veya hukuki metinde yanlış yargı verir. +2. Sessiz düşürme kullanıcıya görünmez. Flag göstermek ve insanın karar vermesi daha iyidir. +3. Audit raporları dataset sürümleri arasında karşılaştırılır; flag sayısındaki ani değişim bilgilendiricidir. + +Daha sıkı filtreleme isterseniz — örneğin pre-training'e giden kamu web crawl'ında — filtreyi uç durumların manuel incelemesi ile birleştirin. + +## Programatik API + +```python +from forgelm.data_audit import score_quality + +text = "= = = = = = = =\n* * *\n[içerik yok]" +flags = score_quality(text) +print(flags) +# {'low_alpha_ratio': True, 'symbol_density': True, 'short_content': True} +``` + +## Sık hatalar + +:::warn +**İncelemeden otomatik düşürme.** `--drop-quality-flags`'i dikkatli ayarlayın — neyin kaldırıldığını size göstermeden satırları kaldırır. Önce neyin flaglendiğini incelemek için `forgelm audit` koşturun. +::: + +:::warn +**Kod dataset'lerini varsayılan eşiklerle filtrelemek.** Kod prose'tan daha çok simge ve daha kısa ortalama kelime uzunluğu içerir. Etkilenen kontrolleri kapatın veya kod-özgü eşikler kullanın. +::: + +## Bkz. + +- [Veri Seti Denetimi](#/data/audit) — kalite filtresini standart audit'in parçası olarak koşturur. +- [Doküman Ingest'i](#/data/ingestion) — çoğu kalite sorunu çıkarma zamanında doğar. diff --git a/docs/usermanuals/tr/data/secrets.md b/docs/usermanuals/tr/data/secrets.md new file mode 100644 index 00000000..e6170416 --- /dev/null +++ b/docs/usermanuals/tr/data/secrets.md @@ -0,0 +1,131 @@ +--- +title: Sırların Temizlenmesi +description: Eğitim verisinden AWS anahtarları, GitHub PAT'leri, JWT'leri, PEM blokları ve diğer kimlik bilgilerini redakte edin. +--- + +# Sırların Temizlenmesi + +Kod repo'ları, destek ticket'ları ve operasyonel log'lar kimlik bilgileri sızdırır. Bu kimlik bilgileri eğitim setine girip model deploy edildikten sonra modelle sohbet eden herkes onları çıkarabilir. Sırların temizlenmesi bunu ingest'te önler. + +## Tespit edilenler + +| Kategori | Tespit edilen pattern | +|---|---| +| **AWS access key'leri** | `AKIA[0-9A-Z]{16}` + secret-key heuristikleri | +| **GitHub PAT'leri** | `ghp_*`, `gho_*`, `ghu_*`, `ghs_*`, `ghr_*` | +| **GitHub fine-grained token'lar** | `github_pat_*` | +| **Slack token'lar** | `xox[bpars]-*` | +| **OpenAI API key'leri** | `sk-*` (uzunluk ve entropi kontrolüyle) | +| **Anthropic API key'leri** | `sk-ant-*` | +| **Google API key'leri** | `AIza*` | +| **JWT'ler** | Üç-segment base64url (header.payload.signature) | +| **PEM özel anahtar blokları** | `BEGIN ... PRIVATE KEY...END` (RSA, EC, OpenSSH, PGP) | +| **Azure storage string'leri** | `DefaultEndpointsProtocol=...` | +| **Stripe / SendGrid / Twilio** | Servis-özgü pattern'ler | + +Tüm eşleşmeler `[REDACTED-SECRET]` (veya `--secrets-tag-by-category` ile kategori başı etiketler) ile değiştirilir. + +## Hızlı örnek + +```shell +$ forgelm ingest ./support-tickets/ \ + --recursive \ + --secrets-mask \ + --output data/tickets.jsonl +✓ 47 sır maskelendi: + aws_access_key: 12 + github_pat: 8 + jwt: 18 + pem_block: 2 + openai_key: 7 +``` + +## "PEM block" ne demek + +PEM özel anahtarlar birden çok satıra yayılır: + +```text +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEA1+... +... +-----END RSA PRIVATE KEY----- +``` + +ForgeLM'in PEM detector'ı tüm bloğu (BEGIN'den END'e) eşleştirir, sadece marker satırını değil. Tüm blok `[REDACTED-PEM-BLOCK]` ile değiştirilir. Bu, BEGIN satırını tespit edip key body'sini JSONL'da bırakan yaygın bug'ı önler. + +## Sadece-audit modu + +```shell +$ forgelm audit data/tickets.jsonl --skip-pii +✓ format: instructions (8,400 satır) +⚠ sırlar: 47 tespit (severity: critical) + 12 AWS access key + 18 JWT + ... +``` + +`critical` severity, `--strict` de geçirirseniz koşuyu başarısız olarak flagler. + +## Programatik API + +```python +from forgelm.data_audit import detect_secrets, mask_secrets + +text = "Şu key'i kullan: AKIAIOSFODNN7EXAMPLE ve JWT eyJhbGc..." +hits = detect_secrets(text) +print(hits) +# [{'category': 'aws_access_key', 'span': (16, 36), 'value': 'AKIAIOSFODNN7EXAMPLE'}] + +cleaned = mask_secrets(text) +# "Şu key'i kullan: [REDACTED-SECRET] ve JWT [REDACTED-SECRET]..." +``` + +## False-positive guard'ları + +ForgeLM tipik "git-secrets" tarzı araçlardan daha sıkı false-positive guard'larıyla sırlar tespiti yayınlar; çünkü: + +1. Eğitim verisinde false positive örnekleri bozar (gerçek string'leri değiştirir). +2. Çoğu sadece-regex pattern `EXAMPLEKEY` veya test fixture'ları flagler; audit raporlarını kullanışsız kılar. + +Spesifik guard'lar: +- OpenAI / Anthropic key'leri için **entropi eşiği** (insan-okunur değil, rastgele görünüm). +- **Bağlam pencere kontrolü** — `AKIA*` sadece secret-key-şeklinde komşu veya 100 karakter içinde "aws" bağlamı varsa tetiklenir. +- **Test/örnek dışlama listesi** — yaygın dummy değerler (`AKIAIOSFODNN7EXAMPLE`, `xxx`, `your_key_here`) `--secrets-strict` ayarlanmadıkça tespiti atlar. + +Yüksek-stake audit (ör. yasal açıklama taraması) için `--secrets-strict` ile bu guard'ları devre dışı bırakıp daha yüksek false-positive oranını kabul edin. + +## Konfigürasyon + +```yaml +ingestion: + secrets_mask: + enabled: true + tag_by_category: true # [REDACTED-SECRET] yerine kategori-özgü etiket + strict: false # false-positive guard'ları kapat + categories: # seçici etkinleştir + - aws_access_key + - github_pat + - jwt + - pem_block + # eklemediğiniz kategori kapalı +``` + +## Sık hatalar + +:::warn +**"Güvenilen iç" veride secrets-mask'i kapatmak.** İç log'lar kimlik bilgisi sızıntılarının en sık kaynağıdır. Maskeleyiciyi koşturmanın maliyeti neredeyse sıfır; deploy edilen modelde sızdırılmış bir AWS key'in maliyeti sınırsız. +::: + +:::warn +**Entropi kontrolsüz özel regex.** Sırlar tespitinde false positive'in en büyük sebebi sadece-regex pattern'lerin dokümantasyon örneklerini eşlemesi. Regex'i her zaman entropi veya bağlam kontrolüyle eşleştirin. +::: + +:::tip +Sertifika / token meşru içeren corpus'lar için (güvenlik eğitim dataset'leri, CTF içeriği) detector'la mücadele etmek yerine `--skip-secrets` kullanın. Gelecek reviewer'ların neden kapatıldığını görmesi için audit log'a istisna belgeleyin. +::: + +## Bkz. + +- [PII Maskeleme](#/data/pii-masking) — kişisel veri için kardeş özellik. +- [Veri Seti Denetimi](#/data/audit) — sadece-audit modunda sırlar tespitini kapsar. +- [Doküman Ingest'i](#/data/ingestion) — secrets-mask'in çağrıldığı yer. diff --git a/docs/usermanuals/tr/data/synthetic-data.md b/docs/usermanuals/tr/data/synthetic-data.md new file mode 100644 index 00000000..a0da14d0 --- /dev/null +++ b/docs/usermanuals/tr/data/synthetic-data.md @@ -0,0 +1,129 @@ +--- +title: Sentetik Veri +description: Teacher-to-student damıtma — daha güçlü bir modelden eğitim verisi üretin. +--- + +# Sentetik Veri + +Gerçek veri kıt veya pahalı olduğunda ek eğitim örneklerini daha güçlü bir modeli prompt'layıp yanıtlarını yakalayarak sentezleyebilirsiniz. ForgeLM'in sentetik-veri pipeline'ı bunu `forgelm --generate-data` ile yapar. + +## Yaygın kullanım senaryoları + +| Kullanım | Ürettiğiniz | +|---|---| +| **Damıtma** | Teacher (ör. GPT-4o) cevap verir; student bu cevaplarda eğitilir. | +| **Veri augmentasyonu** | Mevcut verinizden parafraz veya varyasyon. | +| **Soğuk başlangıç** | Birkaç seed prompt'tan sentetik örnek. | +| **Self-instruct** | Hem prompt hem yanıt üretilir. | + +## Hızlı örnek + +```yaml +synthetic: + enabled: true + teacher: + provider: "openai" # veya "anthropic", "local" + model: "gpt-4o" + api_key: "${OPENAI_API_KEY}" + seed_prompts: "data/seeds.jsonl" # başlangıç prompt'ları + output: "data/synthetic.jsonl" + num_samples: 5000 + temperature: 0.7 + prompt_template: "default" # veya özel template yolu + budget_usd: 50.0 # maliyet tavanı + +training: + trainer: "sft" +datasets: + - path: "data/seeds.jsonl" + - path: "data/synthetic.jsonl" # seed + sentetik birleştir +``` + +```shell +$ forgelm --config configs/distill.yaml --generate-data +[2026-04-29 14:01:32] gpt-4o'dan üretim +[2026-04-29 14:01:35] 100/5000 (şu ana kadar maliyet: $1.20) +[2026-04-29 14:18:55] 5000/5000 (toplam maliyet: $42.30) +✓ data/synthetic.jsonl'a 5000 satır yazıldı +$ forgelm --config configs/distill.yaml # normal eğit +``` + +## Sağlayıcı desteği + +| Sağlayıcı | Modeller | Auth env var | +|---|---|---| +| `openai` | gpt-4o, gpt-4o-mini, o1, o3-mini | `OPENAI_API_KEY` | +| `anthropic` | claude-opus-4, claude-sonnet-4, claude-haiku-4 | `ANTHROPIC_API_KEY` | +| `local` | Herhangi HuggingFace causal LM | yok — yerel inference | +| `vllm` | vLLM üzerinden servis edilen herhangi model | `VLLM_BASE_URL` | + +Yerel üretim için: + +```yaml +synthetic: + teacher: + provider: "local" + model: "Qwen/Qwen2.5-72B-Instruct" + load_in_4bit: true +``` + +## Maliyet kontrolleri + +API tabanlı üretim hızla maliyet biriktirir. ForgeLM sıkı sınırlar yayınlar: + +```yaml +synthetic: + budget_usd: 50.0 # sıkı tavan — üretim burada durur + max_tokens_per_response: 1024 # yanıt uzunluğu sınırı + rate_limit: + requests_per_minute: 100 # sağlayıcı rate-limit'lerine saygı + burst: 10 +``` + +Bütçe dolduğunda ForgeLM kısmi dataset ile durur. Audit log harcanan miktarı tam olarak kaydeder. + +## Kalite kontrolleri + +Sentetik veri sadece iyiyse faydalı. ForgeLM varsayılanları filtreler: + +- **Boş veya tek-token yanıtlar** — API üretim ortasında başarısız oldu; satır düşürüldü. +- **Reddetmeler** — "Bunda yardım edemem" ve benzeri pattern'leri eşleştirir; satır taglenir ama tutulur (güvenlik eğitimi için reddetmeleri tutmak isteyebilirsiniz). +- **Format hataları** — yapılandırılmış prompt'lar için çıktının uyduğunu doğrular. + +## Model card'da atıf + +Sentetik veri üzerinde eğittiğinizde otomatik üretilen model card teacher'ı atıfla anar: + +```markdown +## Eğitim verisi + +Bu model şunlar üzerinde eğitildi: +- 12,000 satır insan-küratör verisi (data/seeds.jsonl) +- openai:gpt-4o tarafından üretilen 5,000 satır sentetik veri (2026-04-29) +``` + +Bu lisans ve ticari kullanım için önemli — bazı teacher'ları damıtmak kaynağı kabul etmeyi gerektirir. + +:::warn +**Teacher'ın hizmet şartlarını kontrol edin.** Bazı sağlayıcılar (özellikle bazı modeller için OpenAI) çıktıların rakip model eğitimi için kullanımını kısıtlar. Model-card atıfı bir *gerçek-iddiası*, *lisans-vermesi* değildir. Kullanımınızın izinli olduğunu doğrulayın. +::: + +## Sık hatalar + +:::warn +**Çok daha küçük student'a teacher damıtma.** 7B student nadiren 405B teacher'ın yeteneklerini yakalar. Gerçekçi oranlar: 70B → 7B çalışır (kalite kaybıyla); 405B → 1.3B çalışmaz. +::: + +:::warn +**Kalite filtresiz self-instruct.** Kendi eğitim verisini üreten modeller güvenli, generic çıktılara doğru drift eder. Düşük-kaliteli sentetik satırları filtrelemek için LLM-as-judge ([Judge](#/evaluation/judge)) uygulayın. +::: + +:::warn +**`temperature`'ı unutmak.** `temperature=0` deterministik yanıt üretir — aynı prompt'a aynı teacher cevabı. Çeşitlilik için `temperature=0.7` veya yüksek kullanın. +::: + +## Bkz. + +- [LLM-as-Judge](#/evaluation/judge) — sentetik veri kalitesini filtrele. +- [Konfigürasyon Referansı](#/reference/configuration) — tam `synthetic:` bloğu. +- [Doküman Ingest'i](#/data/ingestion) — `--format qa` sentetik prompt üretimi kullanır. diff --git a/docs/usermanuals/tr/deployment/chat.md b/docs/usermanuals/tr/deployment/chat.md new file mode 100644 index 00000000..7f9db76e --- /dev/null +++ b/docs/usermanuals/tr/deployment/chat.md @@ -0,0 +1,140 @@ +--- +title: Etkileşimli Chat +description: Akışlı REPL'de güvenlik routing'i ile fine-tuned modelinizi sınayın. +--- + +# Etkileşimli Chat + +`forgelm chat` herhangi bir checkpoint'e karşı akışlı REPL açar — yerel, birleştirilmiş veya LoRA-adapter. Fine-tuning'in istediğiniz modeli üretip üretmediğini doğrulamanın en hızlı yolu. + +## Hızlı örnek + +```shell +$ forgelm chat ./checkpoints/customer-support +ForgeLM 0.5.2 — checkpoints/customer-support ile sohbet +forgelm> aboneliği nasıl iptal ederim? +Aboneliğinizi Ayarlar → Faturalandırma → Aboneliği İptal Et adımlarıyla +iptal edebilirsiniz. Erişiminiz mevcut faturalama döneminin sonuna kadar +devam eder… + +forgelm> /system Türk telekom için kibar bir müşteri-destek temsilcisisin. +[system prompt güncellendi] + +forgelm> tarifeyi nasıl yükseltirim? +Tarifenizi Ayarlar → Plan → Yükselt menüsünden değiştirebilirsiniz... +``` + +## Slash komutları + +| Komut | Yaptığı | +|---|---| +| `/reset` | Konuşma geçmişini temizle. | +| `/save ` | Konuşmayı JSONL'a kaydet. | +| `/load ` | Önceki konuşmayı yükle. | +| `/system ` | System prompt'u ayarla veya güncelle. | +| `/temperature ` | Sampling sıcaklığını ayarla (0.0 - 2.0). | +| `/top_p ` | Nucleus sampling parametresi. | +| `/max_tokens ` | Yanıt uzunluğunu sınırla. | +| `/safety on|off` | Llama Guard pre/post tarayıcısını aç/kapa. | +| `/help` | Bu listeyi göster. | +| `/quit` veya `Ctrl+D` | Çık. | + +## Konfigürasyon + +```yaml +chat: + default_temperature: 0.7 + default_top_p: 0.9 + default_max_tokens: 1024 + default_system_prompt: "Yardımsever bir asistansın." + history_file: "~/.forgelm/chat-history" # oturumlar arası kalıcı +``` + +## Checkpoint yükleme + +`forgelm chat` kabul eder: + +- LoRA adapter ağırlıklı dizin: `./checkpoints/run/` +- Birleştirilmiş checkpoint dizini: `./checkpoints/run/merged/` +- HuggingFace model ID: `Qwen/Qwen2.5-7B-Instruct` +- GGUF dosyası: `./model.gguf` (alta llama.cpp) + +LoRA checkpoint'lerinde base modeli override edebilirsiniz: + +```shell +$ forgelm chat ./checkpoints/run/ --base "Qwen/Qwen2.5-7B" +``` + +## Güvenlik routing'i + +`--safety on` ile her prompt ve yanıt Llama Guard tarafından taranır: + +```text +forgelm> [adversarial prompt] +[Llama Guard S2 (şiddet içermeyen suç) flagledi — reddediliyor] +Bunda yardım edemem. Soruyu farklı şekilde sormayı deneyin. +``` + +Deployment öncesi modeli jailbreak için sondalarken faydalı. Sıradan sohbette varsayılan kapalı. + +## Multi-turn yönetimi + +Konuşma geçmişi bir oturum içinde korunur. Model tüm chat'i (veya `max_length`'a sığanı) görür: + +```text +forgelm> Türkiye'nin başkenti neresi? +Ankara. + +forgelm> nüfusu ne kadar? +[önceki bağlamı kullanır: "nüfusu" Ankara'ya işaret ediyor] +Yaklaşık 5.7 milyon, son tahminlere göre... +``` + +Sıfırdan başlamak için: `/reset`. + +## Kaydetme ve oynatma + +```shell +forgelm> /save sessions/qa-1.jsonl +[6 tur sessions/qa-1.jsonl'a kaydedildi] + +forgelm> /load sessions/qa-1.jsonl +[6 tur yüklendi; devam etmeye hazır] +``` + +Oturumlar şu durumlar için faydalı: +- Test sırasında bulduğunuz bir bug'ı yeniden üretmek. +- İnteraktif keşiften benchmark prompt seti kurmak. +- Aynı konuşmada iki model sürümünü karşılaştırmak. + +## İki modeli karşılaştırma + +```shell +$ forgelm chat-compare ./checkpoints/v1 ./checkpoints/v2 --prompts data/probes.jsonl + v1 (yardımsever) v2 (yardımsever) judge kazanan +"Aboneliği iptal..." ✓ "Ayarlar →" ✓ "Ayarlar →" berabere +"Şifre sıfırlama?" ✓ "Yardım edebil." ✓ "'Şifremi unuttum'a tıkla" v2 +"İade politikası?" ✗ belirsiz ✓ spesifik v2 + ─────── +v1 vs v2 win rate: 0.62 (sig p=0.04) +``` + +## Sık hatalar + +:::warn +**`/temperature 0`'ı determinist saymak.** Yakın-determinist ama argmax sampling'deki eşitlik bozma hâlâ küçük varyans üretebilir. Tam yeniden üretilebilirlik için YAML'da `seed:` ayarlayın. +::: + +:::warn +**Context'i aşan uzun konuşmalar.** Geçmiş `max_length`'i aşınca ForgeLM en eski mesajları düşürür. Konuşma süreklilik kaybedebilir. Uzun test oturumlarında periyodik `/reset` kullanın. +::: + +:::tip +Birçok prompt'un otomatik sondalanması için interaktif REPL yerine `forgelm batch-chat --prompts data/probes.jsonl --output responses.jsonl` kullanın. Aynı model, manuel yazma yok. +::: + +## Bkz. + +- [LLM-as-Judge](#/evaluation/judge) — karşılaştırmayı otomatikleştir. +- [Llama Guard Güvenliği](#/evaluation/safety) — burada da aynı Llama Guard model kullanılır. +- [Deploy Hedefleri](#/deployment/deploy-targets) — memnun kalınca deploy. diff --git a/docs/usermanuals/tr/deployment/deploy-targets.md b/docs/usermanuals/tr/deployment/deploy-targets.md new file mode 100644 index 00000000..42fe753b --- /dev/null +++ b/docs/usermanuals/tr/deployment/deploy-targets.md @@ -0,0 +1,215 @@ +--- +title: Deploy Hedefleri +description: Tek komutla Ollama, vLLM, TGI ve HuggingFace Endpoints deployment config üretin. +--- + +# Deploy Hedefleri + +ForgeLM kendi inference sunucusunu yayınlamaz — bu kapsam dışı. Yerine `forgelm deploy` mevcut başlıca sunucular için çalışmaya hazır config'ler üretir: Ollama, vLLM, TGI ve HuggingFace Endpoints. + +## Hızlı örnek + +```shell +$ forgelm deploy ./checkpoints/customer-support \ + --target ollama \ + --output ./Modelfile +✓ ./Modelfile yazıldı + +$ ollama create my-bot -f ./Modelfile +$ ollama run my-bot +``` + +## Desteklenen hedefler + +| Hedef | Çıktı | Kullanım | +|---|---|---| +| `ollama` | `Modelfile` | Yerel CPU/GPU inference, hızlı prototipleme. | +| `vllm` | `vllm-config.yaml` | Yüksek-throughput GPU servis. | +| `tgi` | `tgi-launcher.sh` + Dockerfile | HuggingFace'in text-generation-inference. | +| `hf-endpoints` | `endpoints-config.json` | HuggingFace Inference Endpoints'a tek-tıkla deploy. | +| `kserve` | `inference-service.yaml` | Kubernetes-yerli model servisi. | +| `triton` | `model_repository/` | NVIDIA Triton Inference Server. | + +## Ollama + +```shell +$ forgelm deploy ./checkpoints/run --target ollama --output Modelfile +``` + +Üretir: + +```text +FROM ./model.q4_k_m.gguf + +SYSTEM "Telekom için kibar müşteri-destek temsilcisisin." + +PARAMETER temperature 0.7 +PARAMETER top_p 0.9 +PARAMETER stop "<|im_end|>" + +# customer-support v1.2.0 checkpoint'inden ForgeLM 0.5.2 ile üretildi +``` + +ForgeLM modelin tokenizer'ına dayanarak doğru `PARAMETER` satırlarını seçer (chat template, stop token) — manuel konfigürasyon gerekmez. + +## vLLM + +```shell +$ forgelm deploy ./checkpoints/run --target vllm --output vllm.yaml +``` + +Üretir: + +```yaml +# vllm.yaml — ForgeLM tarafından üretildi +model: "/data/model" # checkpoint'i /data/model olarak mount et +tokenizer_mode: "auto" +dtype: "bfloat16" +max_model_len: 8192 +gpu_memory_utilization: 0.85 +trust_remote_code: false +served_model_name: "customer-support-v1.2" + +# Chat template tokenizer'dan otomatik algılandı +chat_template: null # tokenizer'ın varsayılanını kullanır +``` + +Çalıştır: + +```shell +$ python -m vllm.entrypoints.openai.api_server --config vllm.yaml --port 8000 +``` + +Yüksek-throughput için ForgeLM model boyutu ve konfigüre GPU sayısına göre tavsiye edilen `--tensor-parallel-size`'ı da üretir. + +## TGI (text-generation-inference) + +```shell +$ forgelm deploy ./checkpoints/run --target tgi --output tgi/ +$ ls tgi/ +launcher.sh Dockerfile config.json +``` + +`launcher.sh`: + +```shell +#!/bin/sh +text-generation-launcher \ + --model-id /data/model \ + --port 8080 \ + --max-input-length 4096 \ + --max-total-tokens 8192 \ + --dtype bfloat16 \ + --quantize bitsandbytes-nf4 +``` + +Dockerfile çok aşamalı ve TGI'nin base imajını çeker — registry'nize push'layın ve `docker run` ile çalıştırın. + +## HuggingFace Endpoints + +```shell +$ forgelm deploy ./checkpoints/run --target hf-endpoints --output endpoints.json +``` + +Çıktı JSON, HuggingFace'in Inference Endpoints create-endpoint API'si için body: + +```shell +$ curl -X POST https://api.endpoints.huggingface.cloud/v2/endpoint \ + -H "Authorization: Bearer $HF_TOKEN" \ + -H "Content-Type: application/json" \ + -d @endpoints.json +``` + +Veya tek-tıkla deployment için HuggingFace UI'sına yapıştırın. + +## KServe (Kubernetes) + +```shell +$ forgelm deploy ./checkpoints/run --target kserve --output kserve.yaml +$ kubectl apply -f kserve.yaml +``` + +`InferenceService` manifest üretir: + +```yaml +apiVersion: "serving.kserve.io/v1beta1" +kind: "InferenceService" +metadata: + name: customer-support-v1.2 +spec: + predictor: + model: + modelFormat: { name: huggingface } + runtime: kserve-huggingfaceserver + storageUri: "s3://my-models/customer-support-v1.2/" + resources: + limits: + nvidia.com/gpu: 1 +``` + +## Triton Inference Server + +```shell +$ forgelm deploy ./checkpoints/run --target triton --output ./model_repository/ +``` + +Triton'un beklediği dizin yapısını üretir: + +```text +model_repository/ +└── customer-support-v1.2/ + ├── 1/ + │ └── model.savedmodel/ + └── config.pbtxt +``` + +## Konfigürasyon + +```yaml +deployment: + target: "vllm" + served_model_name: "customer-support-v1.2" + max_input_length: 4096 + max_total_tokens: 8192 + gpu_memory_utilization: 0.85 + chat_template: "default" # veya .jinja dosyası yolu + system_prompt_default: "Sen..." +``` + +YAML'da `deployment:` varsa `forgelm` son adım olarak (eval / güvenlik geçtikten sonra) `deploy`'u otomatik çalıştırır. + +## Otomatik tespit edilen + +| Ayar | Tespit kaynağı | +|---|---| +| Chat template | Modelin tokenizer config'i | +| Stop token'lar | Tokenizer special token'ları | +| `max_model_len` | Eğitimdeki `model.max_length` | +| Quantization | QLoRA çalıştırdığınız, GGUF export edip etmediğiniz vb. | +| Tensor parallelism | Model boyutu + mevcut GPU | + +Herhangi bir otomatik tespiti açık YAML ile override edebilirsiniz. + +## Sık hatalar + +:::warn +**Deploy edilen quant'ta güvenlik eval'ini atlamak.** Bir q4_k_m GGUF Llama Guard'da full-precision adapter'dan kötü puan alabilir. Deploy edilen artifact üzerinde güvenlik eval'ini tekrar koşturun, sadece eğitim çıktısında değil. +::: + +:::warn +**Generic chat template fallback.** Fine-tune özel chat template kullandıysa otomatik tespit base modelin template'ini (farklı format) seçebilir. Önce `forgelm chat` ile interaktif test edin. +::: + +:::warn +**Eski template'ler.** Modelleri veya tokenizer'ları değiştirdiğinizde deploy config'lerini yeniden üretin. Yeni tokenizer'a işaret eden eski TGI config'i sessizce hatalı çıktı üretir. +::: + +:::tip +ForgeLM'in ürettiği config'ler kaynak run-id ve zaman damgasını içeren bir yorum içerir. Üretilen config'i model release'inizle birlikte commit edin ki geri izleme net olsun. +::: + +## Bkz. + +- [GGUF Export](#/deployment/gguf-export) — Ollama / llama.cpp hedefleri için. +- [Etkileşimli Chat](#/deployment/chat) — deploy etmeden önce test. +- [Uyumluluk Genel Bakış](#/compliance/overview) — release'e ne ekleneceği. diff --git a/docs/usermanuals/tr/deployment/gguf-export.md b/docs/usermanuals/tr/deployment/gguf-export.md new file mode 100644 index 00000000..003f67a8 --- /dev/null +++ b/docs/usermanuals/tr/deployment/gguf-export.md @@ -0,0 +1,148 @@ +--- +title: GGUF Export +description: llama.cpp, Ollama veya LM Studio ile yerel inference için GGUF'a kuantize edin. +--- + +# GGUF Export + +GGUF (GPT-Generated Unified Format), `llama.cpp` üzerinden yerel CPU/GPU inference için fiili dosya formatıdır. ForgeLM herhangi bir fine-tuned checkpoint'i altı kuantizasyon seviyesi ve SHA-256 manifest ile GGUF'a export eder. + +## Hızlı örnek + +```shell +$ forgelm export ./checkpoints/customer-support \ + --output model.gguf \ + --quant q4_k_m +✓ LoRA base'e merge edildi +✓ GGUF'a dönüştürüldü +✓ q4_k_m'a kuantize edildi (4.1 GB → 4.1 GB) +✓ model.gguf ve model.gguf.sha256 yazıldı +``` + +Çıktı tek `.gguf` dosyası artı `.sha256` manifest. + +## Kuantizasyon seviyeleri + +| Seviye | Boyut (7B base) | Kalite | Kullanım | +|---|---|---|---| +| `q8_0` | 7.2 GB | En yüksek | Kalite benchmark; bellek bol üretim. | +| `q6_k` | 5.5 GB | Çok yüksek | Üretim için varsayılan. | +| `q5_k_m` | 4.8 GB | Yüksek | Mantıklı denge. | +| `q4_k_m` | 4.1 GB | İyi | **Yerel inference için varsayılan.** | +| `q3_k_m` | 3.3 GB | Kabul edilebilir | Dar bellek; biraz kalite kaybı. | +| `q2_k` | 2.6 GB | Daha düşük | Edge cihazlar için son çare; belirgin kalite kaybı. | + +`q4_k_m` tatlı nokta — consumer donanıma rahat sığar, full precision'a karşı minimum kalite kaybı. + +## Konfigürasyon + +```yaml +output: + gguf: + enabled: true # eğitimden sonra otomatik export + quant_levels: ["q4_k_m", "q5_k_m"] # tek seferde birden çok seviye + output_dir: "${output.dir}/gguf/" + manifest: true +``` + +`enabled: true` iken ForgeLM `forgelm` koşularının eval'i geçmesinin ardından otomatik export eder. `false` (varsayılan) ise `forgelm export`'u ad hoc kullanın. + +## Çoklu-quant export + +```shell +$ forgelm export ./checkpoints/run \ + --output ./gguf/ \ + --quant "q4_k_m,q5_k_m,q8_0" +✓ gguf/model.q4_k_m.gguf yazıldı (4.1 GB) +✓ gguf/model.q5_k_m.gguf yazıldı (4.8 GB) +✓ gguf/model.q8_0.gguf yazıldı (7.2 GB) +✓ gguf/manifest.json yazıldı +``` + +Manifest: + +```json +{ + "base_model": "Qwen/Qwen2.5-7B-Instruct", + "fine_tune_run_id": "abc123", + "quants": { + "q4_k_m": {"size_bytes": 4100000000, "sha256": "..."}, + "q5_k_m": {"size_bytes": 4800000000, "sha256": "..."}, + "q8_0": {"size_bytes": 7200000000, "sha256": "..."} + }, + "exported_at": "2026-04-29T15:00:00Z" +} +``` + +## GGUF bütünlük doğrulama + +```shell +$ forgelm verify-gguf model.q4_k_m.gguf +✓ valid GGUF magic +✓ vocab boyutu base ile eşleşiyor +✓ sha256 manifest ile eşleşiyor +✓ tokenizer round-trip OK +``` + +Bu kötü transferden bozulmaları, sessiz disk hatalarını ve ara sıra `llama.cpp` upstream uyumsuzluklarını yakalar. + +## Yaygın araçlarda GGUF yükleme + +### Ollama + +```shell +$ cat > Modelfile <<'EOF' +FROM ./model.q4_k_m.gguf +SYSTEM "Kibar bir müşteri-destek temsilcisisin." +PARAMETER temperature 0.7 +EOF +$ ollama create my-bot -f Modelfile +$ ollama run my-bot +``` + +### LM Studio + +`.gguf` dosyasını LM Studio'nun model dizinine bırakın; picker'da görünür. + +### llama.cpp doğrudan + +```shell +$ ./main -m model.q4_k_m.gguf -p "Merhaba, nasılsın?" -n 256 +``` + +## Doğrudan dönüştürme (kuantizasyon yok) + +Nadir olarak fp16 GGUF isterseniz (kuantizasyon-duyarlı bir inference engine için): + +```shell +$ forgelm export ./checkpoints/run --output model.gguf --quant fp16 +``` + +Sonuç full-precision GGUF, 7B model için ~14 GB. + +## Sık hatalar + +:::warn +**LoRA'yı merge etmeden export.** `forgelm export` her zaman LoRA adapter'ı kuantizasyondan önce base'e merge eder. Adapter-only inference istiyorsanız GGUF istemiyorsunuz — adapter'a karşı doğrudan `forgelm chat` kullanın veya PEFT ile yükleyin. +::: + +:::warn +**Tokenizer sürüm uyuşmazlığı.** GGUF tokenizer'ı gömer. Eğitim sonrası tokenizer'ı değiştirirseniz (nadir) GGUF `llama.cpp`'de doğru yüklenmez. Her zaman gerçekten eğitilen checkpoint'ten export edin. +::: + +:::warn +**Orijinale karşı kalite gerilemesi.** Agresif quant'lar (q3, q2) Llama Guard puanlarını kaydırabilir. GGUF üretime gidiyorsa her zaman güvenlik eval'ini yeniden koşturun: +```shell +$ forgelm safety-eval --model model.q4_k_m.gguf --probes data/safety-probes.jsonl +``` +::: + +:::tip +HuggingFace Hub yüklemesi için ForgeLM'in model card'ı GGUF dosyanıza referansla "Ollama ile kullanım" snippet'ı içerir — kopyala-yapıştır hazır. +::: + +## Bkz. + +- [Deploy Hedefleri](#/deployment/deploy-targets) — GGUF dışı deployment seçenekleri. +- [Konfigürasyon Referansı](#/reference/configuration) — `output.gguf` bloğu. +- [Model Birleştirme](#/deployment/model-merging) — export öncesi adapter birleştirme. diff --git a/docs/usermanuals/tr/deployment/model-merging.md b/docs/usermanuals/tr/deployment/model-merging.md new file mode 100644 index 00000000..7468b66b --- /dev/null +++ b/docs/usermanuals/tr/deployment/model-merging.md @@ -0,0 +1,179 @@ +--- +title: Model Birleştirme +description: TIES, DARE, SLERP veya lineer merge ile birden çok LoRA adapter'ı tek modelde birleştirin. +--- + +# Model Birleştirme + +Model birleştirme birden çok fine-tuned modeli (veya LoRA adapter'ı) tek modele toplar. Uzmanlarınız varsa (biri kod, biri destek, biri matematik) ve her birinin yeteneğini koruyacak bir generalist isterseniz faydalı. ForgeLM `forgelm --merge` ile dört birleştirme algoritması destekler. + +## Ne zaman birleştirme + +| Birleştirin: | Birleştirmeyin: | +|---|---| +| Aynı base'de eğitilmiş çoklu LoRA adapter'ı var. | "Uzmanlar" radikal farklı (farklı base, farklı boyut). | +| Çoklu deploy edilebilir model yerine tek model istiyorsunuz. | İstek başına farklı davranış gerek — inference'ta route edin. | +| Sıfırdan eğitim olmadan multi-skill model keşfediyorsunuz. | Üretim güvenilirliği yetenek genişliğinden önemli. | + +Birleştirme her uzmanın kalitesinden biraz feda eder, genişlik kazanır. Birleştirmeden sonra her zaman yeniden değerlendirin. + +## Algoritma seçimi + +| Algoritma | Yaptığı | Parladığı yer | +|---|---|---| +| **Lineer** | Adapter başı katsayılarla ağırlık ortalaması. | Aynı-mimari, iyi-hizalanmış adapter'lar. En basit. | +| **SLERP** | İki adapter arası küresel doğrusal interpolasyon. | İki-yollu birleştirme; manifold geometrisini korur. | +| **TIES** | Trim, Elect-sign, Disjoint-merge. Sıfıra yakın delta'ları düşürür, çatışmayı işaretle çözer. | 3+ adapter; yaygın başlangıç noktası. | +| **DARE** | Drop-and-Rescale. Ağırlık delta'larını rastgele sıfırlar, hayatta kalanları yeniden ölçeklendirir. | Etkileşimi azaltır; TIES ile iyi gider (DARE-TIES). | + +## Hızlı örnek: TIES + +```yaml +merge: + enabled: true + algorithm: "ties" + base_model: "Qwen/Qwen2.5-7B-Instruct" + models: + - path: "./checkpoints/customer-support" + weight: 0.5 + - path: "./checkpoints/code-assistant" + weight: 0.3 + - path: "./checkpoints/math-reasoning" + weight: 0.2 + parameters: + threshold: 0.7 # TIES-özgü: tutulacak delta'ların top-K%'si + output: + dir: "./checkpoints/merged" + model_card: true +``` + +```shell +$ forgelm --merge --config configs/merge.yaml +✓ 3 adapter yüklendi +✓ TIES merge: top %70 delta tutuldu, 1247 işaret çatışması çözüldü +✓ ./checkpoints/merged yazıldı +✓ model card üretildi +``` + +## Hızlı örnek: Lineer + +```yaml +merge: + enabled: true + algorithm: "linear" + base_model: "Qwen/Qwen2.5-7B-Instruct" + models: + - { path: "./checkpoints/v1", weight: 0.5 } + - { path: "./checkpoints/v2", weight: 0.5 } + output: + dir: "./checkpoints/v1-v2-blend" +``` + +Lineer en basit — ağırlıkları ortalar. Başlangıç noktası olarak her zaman çalışır; optimal olmayabilir. + +## Algoritma parametreleri + +| Algoritma | Anahtar parametreler | +|---|---| +| `linear` | Model başı `weights:` | +| `slerp` | `t:` interpolasyon faktörü (0.0 = ilk adapter, 1.0 = ikinci) | +| `ties` | `threshold:` (tutulacak delta'ların top-K%'si, tipik 0.6-0.8), `density:` (alternatif formülasyon) | +| `dare` | `density:` (tutulacak oran, 0.5-0.9), `epsilon:` (yeniden ölçekleme) | +| `dare_ties` | Hem DARE hem TIES parametreleri | + +## Birleştirme sonrası değerlendirme + +Birleştirilmiş modeli her zaman yeniden değerlendirin — herhangi bir girdi modelden farklı bir model. + +```yaml +merge: + enabled: true + algorithm: "ties" + ... + evaluation: + benchmark: + tasks: ["hellaswag", "humaneval", "gsm8k"] # her uzmandan beceri karışımı + floors: + hellaswag: 0.55 + humaneval: 0.40 + gsm8k: 0.50 + safety: + enabled: true +``` + +Birleştirilmiş model herhangi bir görevde gerilerse uzmanlardan birine fallback yapın veya farklı algoritma deneyin. + +## Birleştirme başarısızlıklarını teşhis + +Kötü birleştirme belirtileri: + +| Belirti | Olası sebep | Çözüm | +|---|---|---| +| Tutarlı ama generic çıktı | Lineer merge uzmanlaşmaları ortaladı | `threshold: 0.7` ile TIES dene | +| Bozuk çıktı | Adapter base uyuşmazlığı | Tüm adapter'ların aynı base'i kullandığını kontrol et | +| Her görevde rastgele düşük puan | DARE density çok düşük | `density:`'i 0.9'a yükselt | +| Bir uzman baskın | Lineer ağırlık o adapter için çok yüksek | Ağırlıkları yeniden dengele | + +## Konfigürasyon + +```yaml +merge: + enabled: true + algorithm: "ties" + base_model: "Qwen/Qwen2.5-7B-Instruct" + models: + - path: "./checkpoints/v1" + weight: 0.4 + - path: "./checkpoints/v2" + weight: 0.6 + parameters: + threshold: 0.7 + normalize: true # ağırlıkları 1.0'a normalize et + output: + dir: "./checkpoints/merged" + model_card: true + save_format: "safetensors" +``` + +## Programatik birleştirme + +Otomasyon hatları için: + +```python +from forgelm.merging import merge_adapters + +merge_adapters( + base="Qwen/Qwen2.5-7B-Instruct", + adapters=[ + ("./checkpoints/v1", 0.5), + ("./checkpoints/v2", 0.5), + ], + algorithm="ties", + threshold=0.7, + output_dir="./checkpoints/merged", +) +``` + +## Sık hatalar + +:::warn +**Farklı base'lerde birleştirme.** Qwen2.5-7B'de eğitilen adapter'lar Llama-3-8B'de eğitilenle birleştirilemez — farklı parametre şekilleri. ForgeLM bunu birleştirme zamanında net bir hatayla reddeder. +::: + +:::warn +**Birleştirilmiş modelde eval'i atlamak.** "3 uzmanı birleştirdik"'i "generalist'imiz var" garantisi olarak görmek dilekçe düşüncesidir. Yeniden değerlendirin. +::: + +:::warn +**Birleştirme bileşimi.** A+B'yi birleştirmek, sonucu C ile birleştirmek genelde A+B+C'yi tek seferde birleştirmekten kötüdür. Tek çoklu-yollu merge kullanın. +::: + +:::tip +Keşif birleştirmesi için küçük bir `(algoritma, parametre)` kombinasyonu grid'i üretip her birini değerlendirin. ForgeLM bunu otomatikleştiren bir `forgelm merge-sweep` yardımcısı yayınlar. +::: + +## Bkz. + +- [LoRA, QLoRA, DoRA](#/training/lora) — birleştirilen adapter'ları üretir. +- [Konfigürasyon Referansı](#/reference/configuration) — tam `merge:` bloğu. +- [Sentetik Veri](#/data/synthetic-data) — yetenek genişliği için birleştirmeye alternatif. diff --git a/docs/usermanuals/tr/evaluation/auto-revert.md b/docs/usermanuals/tr/evaluation/auto-revert.md new file mode 100644 index 00000000..dd1c4810 --- /dev/null +++ b/docs/usermanuals/tr/evaluation/auto-revert.md @@ -0,0 +1,142 @@ +--- +title: Otomatik Geri Alma +description: Benchmark veya güvenlik gerilediğinde son-iyi checkpoint'e geri dön. +--- + +# Otomatik Geri Alma + +Başlangıç noktasından daha kötü güvenlik veya kalite skoru alan bir fine-tuned model, hiç fine-tune etmemekten beterdir. Otomatik geri alma ForgeLM'in güvenlik ağıdır: konfigüre edilmiş bir eşik eğitimden sonra başarısız olursa koşu son-iyi checkpoint'e döner ve yapılandırılmış bir olay kaydı bırakır. + +## Karar akışı + +```mermaid +flowchart TD + Start[Eğitim tamamlandı] + Bench{Benchmark
floor'lar geçti mi?} + Safety{Güvenlik
eşikleri geçti mi?} + Loss{Final loss
başlangıca kıyasla?} + OK([Yeni checkpoint'i terfi ettir
exit 0]) + Revert([Son-iyi'ye dön
exit 3]) + Audit[Audit log'a
olay kaydı ekle] + + Start --> Bench + Bench -->|geçemedi| Audit + Bench -->|geçti| Safety + Safety -->|geçemedi| Audit + Safety -->|geçti| Loss + Loss -->|makul| OK + Loss -->|patladı| Audit + Audit --> Revert + + classDef ok fill:#1c2030,stroke:#22c55e,color:#e6e7ec + classDef fail fill:#1c2030,stroke:#ef4444,color:#e6e7ec + classDef question fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + class OK ok + class Revert,Audit fail + class Bench,Safety,Loss question +``` + +## Hangi sinyal geri almayı tetikler + +| Sinyal | Eşik | Konfigüre edilen alan | +|---|---|---| +| Benchmark görevi floor altında | Görev başı `floors:` ayarı | `evaluation.benchmark.floors` | +| Bloklu kategoride güvenlik gerilemesi | `regression_tolerance` (vars. 0.05) | `evaluation.safety.regression_tolerance` | +| Final loss > başlangıç loss | Her zaman | konfigüre edilemez | +| Final loss NaN/Inf | Her zaman | konfigüre edilemez | +| Özel guard başarısız | Kullanıcı verdiği callable | `evaluation.guards.` | + +Bunlardan herhangi biri geri almayı tetikler. + +## Geri alma sırasında ne olur + +1. ForgeLM son-iyi checkpoint'i belirler — DPO başarısız olduğunda genelde SFT checkpoint'i, ya da sürdürülen-eğitim senaryosunda önceki koşunun çıktısı. +2. Son-iyi ağırlıkları konfigüre çıktı dizinine kopyalar (kötü olanların üzerine yazar). +3. `audit_log.jsonl`'a olay kaydı yazar: + +```json +{ + "ts": "2026-04-29T14:33:04Z", + "event": "auto_revert", + "trigger": "safety_regression", + "regressed_categories": ["S5"], + "baseline_safety": {"S5": {"max": 0.08}}, + "post_train_safety": {"S5": {"max": 0.42}}, + "restored_from": "./checkpoints/sft-base", + "exit_code": 3 +} +``` + +4. Opsiyonel olarak webhook fırlatır (Slack, Teams) — bkz. [Webhook'lar](#/operations/webhooks). +5. Exit kodu 3 ile çıkar. + +## Konfigürasyon + +```yaml +evaluation: + auto_revert: + enabled: true + last_good_checkpoint: "./checkpoints/sft-base" + notify_on_revert: true # webhook fırlat + keep_failed_checkpoint: true # inceleme için kötü olanı da sakla + failed_checkpoint_dir: "./checkpoints/failed/" +``` + +`last_good_checkpoint` belirtilmezse ForgeLM koşu başında yüklü olan modeli (girdi modeli) kullanır. + +## Özel guard'lar + +Yerleşik kontrollerin ötesinde ek guard'lar kaydedebilirsiniz: + +```yaml +evaluation: + guards: + custom_metric: + function: "my_module.check_brand_voice" + threshold: 0.7 # fonksiyon ≥ bunu döndürmeli + severity: "critical" +``` + +```python +# my_module.py +def check_brand_voice(checkpoint_path: str) -> float: + """Marka sesi puanını [0, 1] aralığında döndür.""" + # Kendi eval'inizi koşturun... + return 0.82 +``` + +Özel guard'lar aynı geri alma akışına entegre olur. + +## CI/CD entegrasyonu + +Otomatik geri alma CI exit kodlarıyla doğal eşleşir: + +```yaml +# .github/workflows/train.yml +- name: Eğit ve değerlendir + run: forgelm --config configs/run.yaml + # exit 0 = başarı, exit 3 = otomatik geri alma tetiklendi +``` + +Exit 3'ten gelen CI başarısızlıkları *beklenen* — kapı bir gerilemeyi yakalamış demektir. Bastırmayın; araştırın. + +## Sık hatalar + +:::warn +**"Bugün üretime girmek için" otomatik geri almayı kapatmak.** Neredeyse her zaman yanlış karar. Gerçekten göndermeniz gerekiyorsa floor'u tek koşu için açık bir yorumla ve takip issue'sıyla düşürün. Audit log override'ı kaydeder. +::: + +:::warn +**`last_good_checkpoint` silinmiş yola işaret etmek.** Restore hedefini bulamayan otomatik geri alma yüksek sesle başarısız olur. Eğitime başlamadan önce son-iyi checkpoint'i kararlı bir yola pinleyin. +::: + +:::tip +**Otomatik geri almayı sabote ederek test edin.** CI kurulumunda bilerek bir floor'u modelinizin geçemeyeceğini bildiğiniz değere düşürün. Otomatik geri almanın tetiklendiğini, webhook'un postaladığını ve olay kaydının yazıldığını teyit edin. Güvenlik ağını test ederken sorunları keşfetmek, gerçek bir gerilemede keşfetmekten daha iyidir. +::: + +## Bkz. + +- [Benchmark Entegrasyonu](#/evaluation/benchmarks) — floor eşiklerini tanımlar. +- [Llama Guard Güvenliği](#/evaluation/safety) — güvenlik eşiklerini tanımlar. +- [Webhook'lar](#/operations/webhooks) — geri almada bildir. +- [Audit Log](#/compliance/audit-log) — geri alma olaylarının kaydedildiği yer. diff --git a/docs/usermanuals/tr/evaluation/benchmarks.md b/docs/usermanuals/tr/evaluation/benchmarks.md new file mode 100644 index 00000000..d349aad6 --- /dev/null +++ b/docs/usermanuals/tr/evaluation/benchmarks.md @@ -0,0 +1,149 @@ +--- +title: Benchmark Entegrasyonu +description: lm-evaluation-harness görevlerini görev başı floor eşikleriyle ve otomatik geri almayla koşturun. +--- + +# Benchmark Entegrasyonu + +ForgeLM, [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) ile entegre — LLM'ler için standart benchmark suite'i — ve üzerine üretim katmanını ekler: görev başı floor eşikleri, regresyonda otomatik geri alma ve compliance paketinize akan yapılandırılmış artifact'lar. + +## Hızlı örnek + +```yaml +evaluation: + benchmark: + enabled: true + tasks: ["hellaswag", "arc_easy", "truthfulqa", "mmlu"] + floors: + hellaswag: 0.55 + arc_easy: 0.70 + truthfulqa: 0.45 + num_fewshot: 0 # zero-shot eval + batch_size: 8 + output_dir: "./checkpoints/run/artifacts/" +``` + +Eğitimden sonra ForgeLM listelenen görevleri koşturur, floor'larla karşılaştırır ve: +- Tüm görevler floor'u geçerse → koşu başarılı (exit 0) +- Herhangi bir görev floor altına düşerse → son-iyi checkpoint'e otomatik geri al, exit 3 + +## Desteklenen görevler + +`lm-evaluation-harness`'taki her şey çalışır. Sık seçimler: + +| Görev | Ölçtüğü | +|---|---| +| `hellaswag` | Sağduyu tamamlama | +| `arc_easy`, `arc_challenge` | İlkokul fen bilimleri | +| `truthfulqa` | Yaygın yanılgılara dayanıklılık | +| `mmlu` | Geniş çoklu-görev bilgi | +| `winogrande` | Zamir çözümlemesi | +| `gsm8k` | İlkokul matematiği (CoT ile) | +| `humaneval` | Kod tamamlama | + +Türkçe projeler için ForgeLM, Türkçe-özgü görevlere uyarlanmış `mmlu_tr` ve `belebele_tr` şablonları yayınlar. + +## Görev başı floor + +Floor'lar, görev başına post-train'in geçeceği minimum kabul edilebilir puanı tanımlar. *Her* görev kendi floor'unu geçmeden model terfi etmez. + +```yaml +evaluation: + benchmark: + floors: + hellaswag: 0.55 + mmlu: 0.50 + # floor'suz görevler raporlanır ama terfiyi engellemez + truthfulqa: 0.45 +``` + +`null` floor "raporla ama gating yapma" demek. `0` floor floor olmamasıyla aynı. + +:::tip +Floor'ları pre-training baseline'ınızdan biraz altına ayarlayın. Hedef: *iyileştirme* zorunlu kılmak değil, *gerilemeyi* yakalamak. Hedef görevde %5 kazanan ama hellaswag'da %2 kaybeden model genelde iyidir; hellaswag'da %15 kaybeden bozuktur. +::: + +## Pre-train baseline + +Hangi floor'u koyacağınızı bilmek için bir pre-training baseline lazım: + +```shell +$ forgelm benchmark --model "Qwen/Qwen2.5-7B-Instruct" \ + --tasks hellaswag,arc_easy,truthfulqa,mmlu \ + --output baselines/qwen-2.5-7b.json +{"hellaswag": 0.61, "arc_easy": 0.75, "truthfulqa": 0.49, "mmlu": 0.52} +``` + +Makul bir floor baseline eksi 0.03 (stokastik dalgalanma için %3 pay): + +```yaml +evaluation: + benchmark: + floors: + hellaswag: 0.58 # baseline 0.61 - 0.03 + arc_easy: 0.72 + truthfulqa: 0.46 + mmlu: 0.49 +``` + +## Çıktı artifact'ları + +Eval'den sonra ForgeLM şunları yazar: + +```text +checkpoints/run/artifacts/ +├── benchmark_results.json ← görev başı puanlar + floor verdict'leri +└── benchmark_run.log ← tam lm-eval-harness çıktısı +``` + +`benchmark_results.json` yapısı: + +```json +{ + "tasks": { + "hellaswag": { + "score": 0.617, "floor": 0.55, "passed": true, + "fewshot": 0, "n": 10042 + }, + "truthfulqa": { + "score": 0.42, "floor": 0.45, "passed": false + } + }, + "verdict": "regression", + "regressed_tasks": ["truthfulqa"] +} +``` + +CI hatları `verdict`'i parse eder. Gating mantığı için bkz. [Otomatik Geri Alma](#/evaluation/auto-revert). + +## Konfigürasyon parametreleri + +| Parametre | Tip | Vars. | Açıklama | +|---|---|---|---| +| `enabled` | bool | `false` | Ana anahtar. | +| `tasks` | list | `[]` | lm-eval-harness görev adları. | +| `floors` | dict | `{}` | Görev başı minimum kabul edilebilir puan. | +| `num_fewshot` | int | `0` | Zero-shot için 0, 5-shot için 5. | +| `batch_size` | int | `8` | Eval batch size. | +| `limit` | int | `null` | Görev başı satır sınırı — hızlı smoke test için. | +| `device` | string | `"cuda:0"` | Eval cihazı. | + +## Sık hatalar + +:::warn +**Pre-train baseline'dan yüksek floor.** Floor'u base modelin geçemediği değere koyarsanız her koşu başarısız olur — otomatik geri alma devreye girer ve hiç checkpoint alamazsınız. Her zaman `baseline - margin` ile başlayın. +::: + +:::warn +**Yayınlanan kamuya açık sonuçlarla `num_fewshot` uyuşmazlığı.** Kamuya açık leaderboard'lar belirli shot sayılarında raporlar (ör. MMLU kanonik olarak 5-shot). Sonuçların karşılaştırılabilir olmasını istiyorsanız aynı ayarı kullanın. +::: + +:::tip +**`limit` ile iterasyonu hızlandırın.** `limit: 100` ayarlamak görev başına 100 satır koşturur (binlerce yerine) — ~10× hızlı eval. Dev config'lerinde kullanın; üretim için kaldırın. +::: + +## Bkz. + +- [Otomatik Geri Alma](#/evaluation/auto-revert) — floor'lar başarısız olduğunda ne olur. +- [LLM-as-Judge](#/evaluation/judge) — benchmark ötesi nitel eval. +- [Trend İzleme](#/evaluation/trend-tracking) — koşular arası puanları karşılaştırma. diff --git a/docs/usermanuals/tr/evaluation/judge.md b/docs/usermanuals/tr/evaluation/judge.md new file mode 100644 index 00000000..d5bffba4 --- /dev/null +++ b/docs/usermanuals/tr/evaluation/judge.md @@ -0,0 +1,163 @@ +--- +title: LLM-as-Judge +description: OpenAI veya yerel judge modeliyle kalite skorlama — pairwise, single-rubric veya ELO. +--- + +# LLM-as-Judge + +Standart benchmark'lar dar yetenekleri ölçer; "bu yanıt gerçekten iyi mi?" sorusunu yakalamaz. LLM-as-judge bu boşluğu, daha güçlü bir modeli sizinkini değerlendirmek için kullanarak doldurur. ForgeLM üç mod destekler: pairwise karşılaştırma, single-rubric skorlama ve ELO sıralaması. + +## Ne zaman kullan + +| LLM-as-judge: | Benchmark: | +|---|---| +| Çıktı kalitesi öznel (yardımsever, kibar, marka-uyumlu). | Görevin doğrulanabilir cevabı var. | +| Ground truth yok. | Ground truth var. | +| İki modelin nitel çıktısını karşılaştırıyorsunuz. | Mutlak performansı zaman içinde izliyorsunuz. | +| Maliyet kabul edilebilir (GPT-4o-mini ile ~$1-5 / 1K judgement). | Ücretsiz, yerel eval gerek. | + +## Hızlı örnek + +```yaml +evaluation: + judge: + enabled: true + mode: "pairwise" # veya single-rubric, elo + judge_model: + provider: "openai" + model: "gpt-4o-mini" # gpt-4o'dan ucuz, judging için neredeyse aynı kalitede + api_key: "${OPENAI_API_KEY}" + baseline_model: "./checkpoints/sft-base" + test_prompts: "data/eval-prompts.jsonl" + num_samples: 200 + rubric: "default" # veya özel rubric yolu +``` + +## Pairwise mod + +Judge'a sorar: "Yanıt A mı yanıt B mi — hangisi daha iyi, neden?" Win-rate'leri toplar. + +```json +{ + "pairwise_results": { + "wins": 124, + "losses": 56, + "ties": 20, + "win_rate": 0.62, + "judge_explanations_sample": [...] + } +} +``` + +200+ örnekle 0.55 üstü win rate istatistiksel olarak anlamlıdır. Altında daha çok örnek koşturun veya farkın gürültü olduğunu kabul edin. + +## Single-rubric mod + +Judge'dan her yanıtı bir rubric üzerinde puanlamasını ister (kriter başına 1-5 yıldız). + +```yaml +evaluation: + judge: + mode: "single-rubric" + rubric: + criteria: + - name: "yardımseverlik" + description: "Yanıt kullanıcının problemini çözüyor mu?" + scale: 5 + - name: "ton" + description: "Müşteri destek için ton uygun mu?" + scale: 5 + - name: "doğruluk" + description: "İddialar doğru mu?" + scale: 5 +``` + +Çıktı: + +```json +{ + "rubric_means": { + "yardımseverlik": 4.2, + "ton": 4.7, + "doğruluk": 3.8 + } +} +``` + +## ELO mod + +Birden çok model sürümü arasında round-robin pairwise karşılaştırmalar koşturur, ELO puanları hesaplar. + +```yaml +evaluation: + judge: + mode: "elo" + candidates: + - { name: "v1", path: "./checkpoints/v1" } + - { name: "v2", path: "./checkpoints/v2" } + - { name: "v3-current", path: "./checkpoints/v3" } + rounds: 50 +``` + +Çıktı: aday başına ELO puanları. Çok koşu arası karşılaştırma için faydalı (ör. hyperparameter sweep). + +## Judge model seçimi + +| Judge | Maliyet / 1K judgement | Kalite | +|---|---|---| +| `openai:gpt-4o` | ~$5 | En yüksek. Üretim için varsayılan. | +| `openai:gpt-4o-mini` | ~$1 | gpt-4o'nun %90 kalitesi. **Önerilir.** | +| `anthropic:claude-haiku-4` | ~$1.50 | gpt-4o-mini ile karşılaştırılabilir. | +| `local:Qwen2.5-72B-Instruct` | $0 (kendi GPU zamanınız) | Makul; ince yargı çağrılarında daha zayıf. | +| `local:Llama-3.1-70B-Instruct` | $0 | Judging için Qwen 72B'den biraz kötü. | + +## Varyansı azaltma + +Tek judge koşuları gürültülü. ForgeLM standart varyans-azaltma yayınlar: + +- **Self-consistency** — `--num-judgements 3` her karşılaştırmayı üç kez koşturur, çoğunluk alır. +- **Pozisyon swap** — pozisyon önyargısını tespit etmek için A/B'yi değiştirir. +- **Çoklu rubric** — kriterler arası ortalama alır. + +```yaml +evaluation: + judge: + self_consistency: 3 # karşılaştırma başına 3 oy + swap_positions: true # pozisyon önyargısı tespit +``` + +## Maliyet kontrolleri + +```yaml +evaluation: + judge: + budget_usd: 20.0 # $20'da dur + rate_limit: + requests_per_minute: 60 +``` + +Bütçe dolduğunda judge kısmi sonuçlarla durur. + +## Sık hatalar + +:::warn +**Aynı modeli judge ve student olarak kullanmak.** 7B modelin başka 7B çıktılarını yargılaması ince kalite sorunlarını yakalamaz. Daha güçlü judge kullanın. +::: + +:::warn +**Pozisyon önyargısı.** Judge'lar genelde ilk yanıtı biraz tercih eder. Pairwise karşılaştırmalarda her zaman `swap_positions: true`. +::: + +:::warn +**Çok küçük örneklem.** İki modeli 20 prompt'la karşılaştırmak istatistiksel gürültüdür. Anlamlı win-rate için 200+ kullanın. +::: + +:::tip +**Judge'ı benchmark'la birleştirin.** Judge'da kazanıp benchmark'larda gerileyen model, judge'ın tercih ettiği şeyi over-fit ediyor demektir. Her iki sinyal de önemli. +::: + +## Bkz. + +- [Benchmark Entegrasyonu](#/evaluation/benchmarks) — nicel eval eşi. +- [Sentetik Veri](#/data/synthetic-data) — aynı sağlayıcı soyutlaması. +- [Otomatik Geri Alma](#/evaluation/auto-revert) — judge gating sinyali olabilir. diff --git a/docs/usermanuals/tr/evaluation/safety.md b/docs/usermanuals/tr/evaluation/safety.md new file mode 100644 index 00000000..46439232 --- /dev/null +++ b/docs/usermanuals/tr/evaluation/safety.md @@ -0,0 +1,151 @@ +--- +title: Llama Guard Güvenliği +description: 14 zarar kategorisinde güven-ağırlıklı güvenlik skorlama, otomatik geri alma ile entegre. +--- + +# Llama Guard Güvenliği + +Llama Guard, Meta'nın güvenlik-sınıflandırıcı modelleri ailesidir. ForgeLM, Llama Guard'ı güven-ağırlıklı skorlama, ciddiyet katmanları ve trend izleme ile sarmalar — ham bir sınıflandırıcıyı üretim kapısına çevirir. + +## Hızlı örnek + +```yaml +evaluation: + safety: + enabled: true + model: "meta-llama/Llama-Guard-3-8B" + block_categories: ["S1", "S2", "S5", "S10"] + test_prompts: "data/safety-probes.jsonl" + severity_threshold: "high" + output_dir: "./checkpoints/run/artifacts/" +``` + +Her eğitim koşusunun ardından ForgeLM şunları yapar: +1. Ayrılmış güvenlik probe prompt'larına yanıt üretir. +2. Yanıtları 14 Llama Guard kategorisinde skorlar. +3. Pre-train baseline'la ve konfigüre eşiklerle karşılaştırır. +4. Bloklu kategoriler tolerans ötesinde gerilerse otomatik geri almayı tetikler. + +## Zarar kategorileri (S1–S14) + +| Kategori | Açıklama | +|---|---| +| **S1** | Şiddet suçları | +| **S2** | Şiddet içermeyen suçlar | +| **S3** | Cinsel suçlar | +| **S4** | Çocuk istismarı | +| **S5** | Hakaret / iftira | +| **S6** | Uzmanlık tavsiyeleri (hukuki, tıbbi, finansal — yetkisi olmadan) | +| **S7** | Mahremiyet ihlalleri | +| **S8** | Fikri mülkiyet | +| **S9** | Ayrım gözetmeyen silahlar | +| **S10** | Nefret söylemi | +| **S11** | Kendine zarar | +| **S12** | Cinsel içerik | +| **S13** | Seçim / dezenformasyon | +| **S14** | Code interpreter kötüye kullanımı | + +`block_categories`, modelin gerilemesine *izin verilmeyen* kategorilerin listesidir. Diğer kategoriler skorlanır ve raporlanır ama gating tetiklemez. + +## Ciddiyet katmanları + +ForgeLM, Llama Guard'ın kategori-başı çıktılarını ciddiyet katmanlarına gruplar: + +| Katman | Güven aralığı | Aksiyon | +|---|---|---| +| `clean` | Tüm kategoriler 0.10 altında | Geç | +| `low` | Bir veya daha çok kategori 0.10-0.30 | Uyar ama geç | +| `medium` | Kategori(ler) 0.30-0.60 | Bloklu listede değilse logla ve geç; bloklu ise geri al | +| `high` | Herhangi bir kategori > 0.60 | Otomatik geri al | +| `critical` | Bloklu kategori > 0.85 | Otomatik geri al + yapılandırılmış olay kaydı | + +`severity_threshold` katılığı kontrol eder: + +| Ayar | Şu durumda otomatik geri alır | +|---|---| +| `low` | Bloklu kategoride herhangi bir flag | +| `medium` (varsayılan) | Bloklu kategoride güven > 0.30 | +| `high` | Bloklu kategoride güven > 0.60 | +| `critical` | Bloklu kategoride güven > 0.85 | + +## Pre-train baseline + +Llama Guard'ı kapı olarak kullanmadan önce *base* modelinizi skorlayın: + +```shell +$ forgelm safety-eval --model "Qwen/Qwen2.5-7B-Instruct" \ + --probes data/safety-probes.jsonl \ + --output baselines/safety-qwen-7b.json +``` + +Bu, karşılaştırma noktasıdır — otomatik geri alma fine-tune'un baseline'ın altına *gerilemesi* durumunda tetiklenir, mutlak skor kötü olduğunda değil. Fine-tuning güvenliği nadiren iyileştirir; hedef onu kötüleştirmemek. + +## Probe prompt tasarımı + +Probe seti şöyle olmalı: + +- **Temsili** — deploy edilen yüzeyin (müşteri-destek, kod, vb.) gerçeğine uygun. +- **Adversarial** — bilinen jailbreak pattern'leri ve kategori-özgü probe'ları içerir. +- **Etiketli** — her probe hedeflediği kategoriyle taglenmiş. + +ForgeLM `forgelm safety-eval --default-probes` ile varsayılan 200-prompt probe seti gönderir. Kendi setinizle genişletin. + +## Çıktı artifact'ları + +```text +checkpoints/run/artifacts/ +├── safety_report.json ← kategori başı güven puanları +├── safety_examples.jsonl ← inceleme için en kötü flaglenen 10 yanıt +└── safety_run.log ← tam Llama Guard çıktıları +``` + +`safety_report.json`: + +```json +{ + "model": "meta-llama/Llama-Guard-3-8B", + "categories": { + "S1": {"max": 0.04, "mean": 0.01, "regressed": false}, + "S5": {"max": 0.42, "mean": 0.08, "regressed": true}, + ... + }, + "verdict": "regression", + "regressed_blocked_categories": ["S5"] +} +``` + +## Konfigürasyon parametreleri + +| Parametre | Tip | Vars. | Açıklama | +|---|---|---|---| +| `enabled` | bool | `false` | Ana anahtar. | +| `model` | string | `"meta-llama/Llama-Guard-3-8B"` | Llama Guard varyantı. | +| `block_categories` | list | `[]` | Gerilemesine izin verilmeyen kategoriler. | +| `test_prompts` | string | (yerleşik) | JSONL probe seti yolu. | +| `severity_threshold` | string | `"medium"` | Katılık. | +| `regression_tolerance` | float | `0.05` | Baseline'a karşı izin verilen maksimum gerileme (%5). | +| `baseline` | string | `null` | Pre-train baseline JSON'u. | + +## Sık hatalar + +:::warn +**`block_categories`'yi "tüm 14"'e ayarlamak.** Model bir şeye gerileyecektir — genelde S5 (iftira) veya S6 (uzmanlık tavsiyesi). Deployment'ınız için önemli olanı bloklayın, hepsini değil. +::: + +:::warn +**Probe seti çok küçük.** Bloklu kategori başına 100'den az probe kararsız puan üretir. Yerleşik 200-prompt seti minimum kabul edin. +::: + +:::warn +**Llama Guard belleği.** Llama Guard 3 8B kendi başına ~16 GB ister. Eğitiminiz zaten VRAM'i sonuna kadar kullanıyorsa güvenlik eval'ini aynı süreçte değil ayrı aşama olarak çalıştırın. +::: + +:::tip +**Llama Guard verdict'lerini zaman içinde izleyin.** Birkaç koşudur sürekli yükselen kategori, bir kerelik sıçramadan daha önemlidir. Bkz. [Trend İzleme](#/evaluation/trend-tracking). +::: + +## Bkz. + +- [Otomatik Geri Alma](#/evaluation/auto-revert) — güvenlik gerilediğinde ne olur. +- [Trend İzleme](#/evaluation/trend-tracking) — uzun-dönem güvenlik trendleri. +- [Uyumluluk Genel Bakış](#/compliance/overview) — güvenlik raporlarının audit paketine akışı. diff --git a/docs/usermanuals/tr/evaluation/trend-tracking.md b/docs/usermanuals/tr/evaluation/trend-tracking.md new file mode 100644 index 00000000..ab3dd3a5 --- /dev/null +++ b/docs/usermanuals/tr/evaluation/trend-tracking.md @@ -0,0 +1,130 @@ +--- +title: Trend İzleme +description: Eval sonuçlarını koşular arası karşılaştırın — eşikleri aşmadan önce yavaş drift'leri yakalayın. +--- + +# Trend İzleme + +Koşu başı eşikler regresyonları yakalar; trend izleme drift'i yakalar. Beş koşudur sürekli yükselen kategori, bir kerelik sıçramadan farklı (ve genelde daha önemli) bir sinyaldir. ForgeLM eval sonuçlarını proje başına geçmiş dosyasında saklar ve her koşuda trend raporlar. + +## Hızlı örnek + +Aynı projenin birkaç koşusundan sonra audit raporuna trend bölümü dahil olur: + +```json +{ + "trend": { + "lookback_runs": 10, + "benchmark": { + "hellaswag": {"trend": "stable", "delta_per_run": 0.001}, + "truthfulqa": {"trend": "drifting_down", "delta_per_run": -0.012, "concern": "medium"} + }, + "safety": { + "S5": {"trend": "drifting_up", "delta_per_run": 0.04, "concern": "high"}, + "S10": {"trend": "stable", "delta_per_run": 0.001} + } + } +} +``` + +`concern` seviyeleri: + +| Seviye | Tetikleyici | +|---|---| +| `none` | Lookback penceresinde drift yok. | +| `low` | İstatistiksel drift var ama küçük. | +| `medium` | Sabit drift; mevcut hızla ~10 koşuda eşiğe çarpacak. | +| `high` | Sabit drift; ~3 koşuda eşiğe çarpacak. | +| `critical` | Eşiğe yakın VE drift devam ediyor. | + +## Drift nasıl hesaplanır + +Her metrik (benchmark görevi veya güvenlik kategorisi) için: + +1. Proje geçmişinden son N koşuyu çek. +2. Puanı koşu indeksine karşı doğrusal regresle. +3. Slope'u t-testle sıfıra karşı test et. +4. Slope anlamlı *ve* büyüklüğü gürültü tabanının üstündeyse drift raporla. + +`lookback_runs` varsayılan 10 — eğitim sıklığınıza göre ayarlayın. + +## Konfigürasyon + +```yaml +evaluation: + trend: + enabled: true + history_file: "./.forgelm/eval-history.jsonl" + lookback_runs: 10 + drift_p_threshold: 0.05 # istatistiksel anlamlılık + fail_on_concern: "high" # drift 'high' olursa exit 3 +``` + +`fail_on_concern: high` trend izlemeyi "tavsiye"den "gating"e yükseltir — CI'nız sadece koşu başı regresyonlarda değil, soruna doğru giden drift'lerde de başarısız olur. + +## Geçmiş dosyası nerede + +Varsayılan `.forgelm/eval-history.jsonl`, proje kök dizininde. Her koşu bir satır ekler: + +```json +{"ts": "2026-04-29T14:33:04Z", "run_id": "abc123", "config_hash": "deadbeef", "benchmark": {...}, "safety": {...}} +``` + +Bu dosyayı commit edin. Küçüktür (koşu başına bir satır, JSON) ve CI koşuları ile katkıda bulunanlar arası trend izlemenin tek yoludur. + +## Görselleştirme + +ForgeLM bir CLI raporu yayınlar: + +```shell +$ forgelm trend --metric "safety.S5" --lookback 20 + +S5 (iftira) — son 20 koşu: + + 0.42 ┤ ╭────● + 0.30 ┤ ╭─────╯ + 0.18 ┤ ╭───────────╯ + 0.06 ┤ ●─────●─────●─────●────────╯ + └─┴───────────────────────────────────────────────────┘ + 1 3 5 7 9 11 13 15 17 19 20 + +Doğrusal fit: slope=+0.018/koşu, p=0.001 — yukarı drift (high concern) +``` + +Dashboard için JSONL Grafana veya Datadog'a kolay yüklenir: + +```shell +$ jq '.benchmark.truthfulqa, .ts' .forgelm/eval-history.jsonl > truthfulqa-trend.csv +``` + +## Koşu tanımlama + +Her koşunun `run_id` (UUID) ve `config_hash` (YAML config'in hash'i) vardır. Koşuları karşılaştırırken benzer-için-benzer karşılaştırın — hyperparam değişikliği, regresyon olmadan baseline'ı kaydırabilir. + +Geçmişi filtrele: + +```shell +$ forgelm trend --metric "benchmark.hellaswag" \ + --filter "config_hash=deadbeef" \ + --lookback 30 +``` + +## Sık hatalar + +:::warn +**Config-değişen koşularla config-sabit koşuları karıştırmak.** Farklı config'li koşular arasında hesaplanan trend anlamsızdır. Benzer-için-benzer için `--filter config_hash` kullanın. +::: + +:::warn +**Çok kısa lookback.** `lookback_runs: 3` ile her rastgele dalgalanma drift gibi görünür. Kararlı sinyal için 10+'da kalın. +::: + +:::tip +**Geçmişi açıklayın.** Bilerek bir şey değiştirdiğinizde (yeni dataset, yeni hyperparam) `.forgelm/eval-history.jsonl`'a baseline'ların neden kayabileceğini açıklayan bir not commit edin. Gelecekteki kendiniz şimdiki kendinize teşekkür edecek. +::: + +## Bkz. + +- [Benchmark Entegrasyonu](#/evaluation/benchmarks) — veriyi üretir. +- [Llama Guard Güvenliği](#/evaluation/safety) — güvenlik puanlarını üretir. +- [Otomatik Geri Alma](#/evaluation/auto-revert) — koşu başı odaklı kardeş kapı. diff --git a/docs/usermanuals/tr/getting-started/first-run.md b/docs/usermanuals/tr/getting-started/first-run.md new file mode 100644 index 00000000..99ad1e83 --- /dev/null +++ b/docs/usermanuals/tr/getting-started/first-run.md @@ -0,0 +1,146 @@ +--- +title: İlk Koşunuz +description: 5 dakikada ilk ForgeLM eğitiminizi koşturun — kur, doğrula, eğit, değerlendir. +--- + +# İlk Koşunuz + +Bu sayfa sıfır `pip install`'tan denetim artifact'larıyla bitmiş bir checkpoint'e kadar tam bir eğitim koşusunda yürür. ~5 dakika okuma ve ~30 dakika GPU zamanı planlayın. + +```mermaid +flowchart LR + A[pip install] --> B[forgelm doctor] + B --> C[forgelm quickstart] + C --> D[--dry-run] + D --> E[--fit-check] + E --> F[Eğitim] + F --> G[Eval + Annex IV] + G --> H[forgelm chat] + classDef setup fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + classDef validate fill:#1c2030,stroke:#eab308,color:#e6e7ec + classDef run fill:#1c2030,stroke:#22c55e,color:#e6e7ec + class A,B,C setup + class D,E validate + class F,G,H run +``` + +## 1. Ortamı doğrula + +Her şeyden önce Python, PyTorch, CUDA ve opsiyonel bağımlılıkların doğru bağlandığını kontrol etmek için `forgelm doctor` çalıştırın: + +```shell +$ forgelm doctor +ForgeLM 0.5.2 +Python 3.11.4 · PyTorch 2.4.0 +CUDA available · driver 535.171 · NVIDIA RTX 4090 · 24 GB +bitsandbytes ✓ (installed) +Unsloth ✓ (installed) +``` + +:::tip +`forgelm doctor` bir sorun raporlarsa (eksik CUDA, sürüm uyumsuzluğu, GPU yok), önce onu düzeltin. Diğer her ForgeLM komutu kafa karıştırıcı şekillerde patlar. Bkz. [Sorun Giderme](#/operations/troubleshooting). +::: + +## 2. Yerleşik bir şablon seç + +ForgeLM, gerçek-dünya fine-tuning senaryolarının çoğunu kapsayan beş başlangıç şablonuyla gelir. Listele: + +```shell +$ forgelm quickstart --list + customer-support Multi-turn helpful + safe (SFT + DPO) + code-assistant Code-completion fine-tune (SFT + ORPO) + byod-domain-expert PDF/DOCX corpus → domain Q&A (SFT) + medical-qa-tr Turkish medical Q&A (SFT) + math-reasoning Step-by-step reasoning (GRPO) +``` + +İlk koşunuz için `customer-support` seçin — küçük, 12 GB GPU'da ~30 dakikada biter ve her özelliği egzersiz eder (SFT, DPO, eval, güvenlik, audit): + +```shell +$ forgelm quickstart customer-support +Wrote configs/quickstart-customer-support.yaml +``` + +Üretilen YAML sizin — saklayın, düzenleyin, version-control'e alın. Açın. + +## 3. Konfigürasyonu doğrula (`--dry-run`) + +Eğitimden önce daima doğrulayın. `--dry-run` YAML'ınızı parse eder, her referans verilen dosyanın varlığını kontrol eder, model ve tokeniser metadata'sını indirir, yapısal sorunları raporlar — tek GPU saniyesi harcamadan: + +```shell +$ forgelm --config configs/quickstart-customer-support.yaml --dry-run +✓ config validates +✓ datasets reachable +✓ tokenizer downloadable +✓ output directory writable +``` + +:::warn +Başarısız `--dry-run` bir konfigürasyon problemidir, eğitim problemi değil. Daha ileri gitmeden düzeltin. "Eğitim step 0'da çöktü" raporlarının çoğu atlanmış dry-run'lara dayanır. +::: + +## 4. VRAM tahmini (`--fit-check`) + +Farklı modeller, farklı `max_length`, farklı LoRA rank'leri peak memory'i değiştirir. `--fit-check` statik analiz çalıştırır ve işinizin sığıp sığmayacağını raporlar: + +```shell +$ forgelm --config configs/quickstart-customer-support.yaml --fit-check +FITS est. peak 11.4 GB / 12 GB available +``` + +Olası verdict'ler: + +| Verdict | Anlamı | +|---|---| +| `FITS` | VRAM bütçesi rahat. Devam edin. | +| `TIGHT` | Bütçe içinde ama activation patlamaları için pay yok. `max_length` veya batch size'ı düşürün. | +| `OOM` | Sığmayacak. Önerilen düzeltmeler basılır (ör. QLoRA aç, batch size düşür). | +| `UNKNOWN` | Mimari GPU profil veritabanında yok — muhafazakar koşun veya bildirin. | + +## 5. Eğit + +```shell +$ forgelm --config configs/quickstart-customer-support.yaml +[2026-04-29 14:01:32] config validated +[2026-04-29 14:01:33] auditing data/customer-support.jsonl (12,400 rows, 3 splits) +[2026-04-29 14:01:35] PII flags: 0 critical, 5 medium · cross-split overlap: 0 +[2026-04-29 14:01:37] SFT epoch 1/3 · loss=2.31 → 1.42 +[2026-04-29 14:18:55] DPO preference pass · β=0.1 · KL=4.2 +[2026-04-29 14:32:11] benchmark hellaswag=0.62 truthfulqa=0.48 +[2026-04-29 14:33:02] Llama Guard S1-S14: clean +[2026-04-29 14:33:04] Annex IV → checkpoints/customer-support/artifacts/annex_iv.json +[2026-04-29 14:33:04] ✔ finished, exit 0 +``` + +## 6. Modeli dene + +```shell +$ forgelm chat ./checkpoints/customer-support +forgelm> aboneliği nasıl iptal ederim? +Aboneliğinizi Ayarlar → Faturalandırma → Aboneliği İptal Et adımlarıyla iptal edebilirsiniz. +Erişiminiz mevcut faturalama döneminin sonuna kadar devam eder… +``` + +## Diskte ne var + +```text +checkpoints/customer-support/ +├── artifacts/ +│ ├── annex_iv.json ← Article 11 teknik dokümantasyon +│ ├── audit_log.jsonl ← Article 12 append-only event log +│ ├── data_audit_report.json ← Article 10 veri yönetimi kanıtı +│ ├── safety_report.json ← Llama Guard verdict +│ ├── benchmark_results.json ← Görev başı doğruluk +│ └── manifest.json ← Her artifact üzerinde SHA-256 +├── README.md ← Article 13 model card +├── config_snapshot.yaml ← Bu koşunun kullandığı tam YAML +└── adapter_model.safetensors ← LoRA ağırlıkları (veya birleştirilmiş checkpoint) +``` + +O `artifacts/` dizini compliance incelemeleri için teslim edilebilirdir. İçindeki her dosya `manifest.json`'da tamper-evidence için hashlenmiştir. + +## Sıraki adımlar + +- [Proje Yapısı](#/getting-started/project-layout) — ForgeLM şeyleri nereye ve neden koyar. +- [Trainer Seçimi](#/concepts/choosing-trainer) — `customer-support`'tan kendi kullanım senaryonuza geçiş. +- [Konfigürasyon Referansı](#/reference/configuration) — her YAML alanı detayıyla. diff --git a/docs/usermanuals/tr/getting-started/installation.md b/docs/usermanuals/tr/getting-started/installation.md new file mode 100644 index 00000000..19719ecf --- /dev/null +++ b/docs/usermanuals/tr/getting-started/installation.md @@ -0,0 +1,130 @@ +--- +title: Kurulum +description: ForgeLM'i PyPI'dan kurun; ingest, ölçek ve export için opsiyonel extra'larla. +--- + +# Kurulum + +ForgeLM, PyPI'da tek bir paket olarak gelir; ağır özellikler için opsiyonel bağımlılık grupları (*extras*) vardır. Çoğu kullanıcı temel kurulumla başlayıp ihtiyaç duydukça extra ekler. + +## Gereksinimler + +| Gereksinim | Asgari | Önerilen | +|---|---|---| +| Python | 3.10 | 3.11+ | +| OS | Linux, macOS | GPU eğitimi için Linux | +| RAM | 8 GB | 16 GB+ | +| Disk | 5 GB boş | Model cache'leri için 50 GB+ | +| GPU (eğitim) | Ingest/audit için yok | SFT 7B için en az tek 12 GB CUDA GPU | + +:::note +**GPU yok mu?** ForgeLM'i ingest, audit, eval hazırlığı ve deployment config üretimi için yine de kullanabilirsiniz — her CPU-only iş akışı aynı `forgelm` komutuyla çalışır. +::: + +## Temel kurulum + +```shell +$ pip install forgelm +``` + +Bu size trainer'ı, altı alignment paradigmasını, değerlendirmeyi, güvenlik skorlamasını, uyumluluk artifact üretimini ve CLI'yı verir. Veriniz zaten JSONL formatındaysa modeli uçtan uca fine-tune etmek için yeterlidir. + +Kurulumu doğrulayın: + +```shell +$ forgelm --version +$ forgelm --help +``` + +## Opsiyonel extra'lar + +ForgeLM ağır veya nadir gereken bağımlılıkları extra'lara ayırır; ihtiyaç duymadığınız sürece kurulmazlar. + +### Doküman ingest'i (`[ingestion]`) + +```shell +$ pip install 'forgelm[ingestion]' +``` + +PDF, DOCX, EPUB, TXT ve Markdown dosyalarını `forgelm ingest` ile SFT-hazır JSONL'a dönüştürmek için. `pypdf`, `python-docx`, `ebooklib` ve birkaç küçük metin işleme kütüphanesini ekler. + +### Büyük corpus dedup'ı (`[ingestion-scale]`) + +```shell +$ pip install 'forgelm[ingestion-scale]' +``` + +~50K satırdan büyük corpus'larda near-duplicate tespiti için MinHash LSH (`datasketch` üzerinden) ekler. Varsayılan simhash detector hızlı ve kesin recall sağlar; MinHash milyonlarca satıra ölçeklenir. Sadece ölçek lazımsa kurun. + +### GGUF export (`[export]`) + +```shell +$ pip install 'forgelm[export]' +``` + +Yerel inference için (Ollama, llama.cpp) kuantize GGUF export'u ekler. `gguf` writer'ı ve destekleyici kütüphaneleri kurar. Opsiyonel çünkü her iş akışı GGUF ile bitmez — birçok kullanıcı doğrudan vLLM veya TGI'a teslim eder. + +### Dağıtık eğitim (`[deepspeed]`) + +```shell +$ pip install 'forgelm[deepspeed]' +``` + +Çoklu-GPU eğitim için DeepSpeed ZeRO-2 / ZeRO-3 desteği ekler. Sadece tek GPU'ya sığmayan model eğitiyorsanız gerekli. + +### Her şey (`[all]`) + +```shell +$ pip install 'forgelm[all]' +``` + +Tüm extra'ları çeker. Tüm kod yollarını test etmesi gereken CI runner'ları için kullanışlı; minimal bağımlılık ağacı isteyen üretim ortamları için önerilmez. + +## Container kurulumu + +Python bağımlılıklarını ana makinenize kurmak istemiyorsanız resmi Docker imajı tüm extra'larla ForgeLM'i paketler: + +```shell +$ docker pull ghcr.io/cemililik/forgelm:latest +$ docker run --gpus all -v $PWD:/workspace ghcr.io/cemililik/forgelm:latest \ + forgelm --config /workspace/configs/run.yaml +``` + +Bir `docker-compose.yml` de yayınlanmıştır; çoklu-servis pattern (eğitim + deney takibi + webhook receiver) için bkz. [Docker Operasyonu](#/operations/docker). + +## GPU erişimini doğrulama + +GPU eğitimi için kurduysanız CUDA'nın doğru bağlandığını teyit edin: + +```shell +$ forgelm doctor +``` + +`forgelm doctor` şunları raporlar: +- Python ve PyTorch sürümleri +- CUDA varlığı ve sürücü sürümü +- Algılanan GPU modeli ve VRAM +- Mevcut compute capability +- bitsandbytes / Unsloth tespiti (kuruluysa) + +:::tip +Yeni bir ortamda `forgelm --config ...` koşmadan *önce* `forgelm doctor` çalıştırın. Eksik CUDA kütüphanelerini, sürüm uyumsuzluklarını ve "GPU bulunamadı" hatalarını eğitime saatler kala değil saniyeler içinde yakalar. +::: + +## Sık karşılaşılan kurulum sorunları + +:::warn +**macOS / Apple Silicon'da `bitsandbytes` import hatası.** `bitsandbytes` şu an Metal/MPS'i desteklemiyor. macOS'ta ForgeLM full precision eğitime düşer. 4-bit kuantize eğitim (QLoRA) için CUDA GPU'lu bir Linux makine gerekir. +::: + +:::warn +**`undefined symbol: __cudaRegisterFatBinaryEnd`.** PyTorch ve CUDA toolkit sürümleriniz uyumsuz. PyTorch'u CUDA sürümünüze uyacak şekilde tekrar kurun: `pip install torch --index-url https://download.pytorch.org/whl/cu121` (`cu121`'i kendi CUDA sürümünüzle değiştirin). +::: + +:::warn +**`OSError: HuggingFace token not found`.** Bazı modeller (ör. Llama 3, Llama Guard) HuggingFace access token gerektirir. `huggingface-cli login` ile veya `HF_TOKEN` environment variable üzerinden ayarlayın. Tüm auth env var'ları için bkz. [CLI Referansı](#/reference/cli). +::: + +## Sıraki adımlar + +ForgeLM kurulu olduğuna göre uçtan uca eğitim turu için [İlk Koşunuz](#/getting-started/first-run)'a geçin — yaklaşık 5 dakikalık okuma ve 30 dakikalık GPU süresinde fine-tuned bir modeliniz olacak. diff --git a/docs/usermanuals/tr/getting-started/introduction.md b/docs/usermanuals/tr/getting-started/introduction.md new file mode 100644 index 00000000..8ba1d0d2 --- /dev/null +++ b/docs/usermanuals/tr/getting-started/introduction.md @@ -0,0 +1,107 @@ +--- +title: Tanıtım +description: ForgeLM nedir, kim için, neler yapabilirsiniz. +--- + +# ForgeLM'e Hoş Geldiniz + +**ForgeLM, YAML temelli, kurumsal seviyede bir LLM fine-tuning araç setidir.** Konfigürasyon dosyası girersiniz; size fine-tuned model, denetim kayıtları, güvenlik raporu ve regülatörün görmek isteyeceği Annex IV teknik dokümantasyonu döner. + +Bu kullanım rehberi her özelliği detayıyla anlatır — kavramlar, konfigürasyon parametreleri, sık yapılan hatalar ve kendi iş akışlarınıza uyarlayabileceğiniz kopyala-yapıştır YAML örnekleri. + +## Bu rehber kimin için + +ForgeLM özellikle üç kitle için yapıldı: + +- **ML mühendisleri** — fine-tuned modelleri regülasyonlu üretime alması gereken, yeniden üretilebilir, scriptlenebilir bir iş akışı isteyen. +- **Compliance ekipleri** — modelin eğitim verisi, değerlendirmesi ve deploymentının EU AI Act, KVKK / GDPR veya sektör-özgü gereklere uygun olduğunu denetçiye gösterebilmesi gereken. +- **Platform / MLOps mühendisleri** — eğitimi CI/CD hatlarının parçası olarak çalıştıran; tahmin edilebilir exit kodlar, yapılandırılmış log ve webhook entegrasyonu isteyen. + +LLM fine-tuning'e yeniyseniz [Temel Kavramlar](#/concepts/alignment-overview) bölümü konfigürasyona geçmeden önce arkadaki fikirleri açıklar. + +## ForgeLM ile neler yapılır + +:::tip +Aşağıdaki her yetenek YAML üzerinden opt-in. Karmaşıklık maliyetini sadece etkinleştirdiğiniz özellikler için ödersiniz. +::: + +| Aşama | ForgeLM'in size sunduğu | +|---|---| +| **Veri hazırlığı** | PDF / DOCX / EPUB / TXT / Markdown ingest'i, PII maskeleme, sırların temizlenmesi, near-duplicate tespiti, kalite filtresi, dil tespiti, split-arası sızıntı kontrolü | +| **Eğitim** | Altı post-training paradigması (SFT, DPO, SimPO, KTO, ORPO, GRPO), QLoRA / DoRA / GaLore, DeepSpeed ZeRO-2/3, FSDP, Unsloth backend | +| **Değerlendirme** | `lm-evaluation-harness` entegrasyonu, OpenAI veya yerel modelle LLM-as-judge, otomatik geri alma ile Llama Guard güvenlik skorlaması | +| **Uyumluluk** | EU AI Act Annex IV artifact üretimi, SHA-256 manifest'li append-only audit log, uygunluk beyanı şablonları | +| **Deployment** | 6 kuantizasyon seviyesi ile GGUF export, Ollama / vLLM / TGI / HuggingFace Endpoints için deployment config, otomatik model card üretimi | + +## Bir ForgeLM koşusu nasıl akar + +```mermaid +flowchart LR + A[Ham doküman
veya JSONL] --> B[forgelm ingest] + B --> C[forgelm audit] + C -->|PII / sızıntı
flagleninir| C + C --> D[--dry-run
--fit-check] + D --> E[forgelm
eğitim] + E --> F[Benchmark
+ güvenlik eval] + F -->|regresyon| G[Otomatik
geri alma] + G --> E + F -->|geçer| H[Annex IV
artifact'ları] + H --> I[Export ve
deploy] + classDef start fill:#1c2030,stroke:#f97316,color:#e6e7ec + classDef ok fill:#161a24,stroke:#22c55e,color:#e6e7ec + classDef warn fill:#161a24,stroke:#eab308,color:#e6e7ec + classDef end1 fill:#1c2030,stroke:#0ea5e9,color:#e6e7ec + class A start + class B,C,D ok + class E,F warn + class G,H,I end1 +``` + +Her node bir `forgelm` komutuna karşılık gelir — toolkit dışında yaşayan bir orkestratör yok. CI/CD sistemleri bu komutları exit kodlarıyla kapı olarak zincirler. + +## Bu rehber nasıl düzenlendi + +Sol menü konuları yaşam döngüsü aşamasına göre gruplar: + +1. **Başlarken** — kurulum, ilk eğitim koşusu, proje yapısı. +2. **Temel Kavramlar** — alignment yığını, trainer seçimi, veri seti formatları. +3. **Eğitim ve Alignment** — her trainer (SFT, DPO, SimPO, KTO, ORPO, GRPO) ve her parametre-verimli yöntem (LoRA, QLoRA, DoRA, GaLore). +4. **Veri** — ingest, denetim, maskeleme, dedup. +5. **Değerlendirme ve Güvenlik** — benchmark, judge, Llama Guard, otomatik geri alma. +6. **Uyumluluk** — Annex IV, audit log, KVKK / GDPR. +7. **Operasyon** — CI/CD, webhook, dağıtık eğitim, air-gap, sorun giderme. +8. **Deployment** — chat, GGUF, deploy hedefleri, model birleştirme. +9. **Referans** — tam konfigürasyon şeması, CLI referansı, exit kodları. + +## Nereden başlamalı + +:::note +**ForgeLM'e yeniyseniz?** [Kurulum](#/getting-started/installation) ve [İlk Koşunuz](#/getting-started/first-run) sıralı okuyun — yaklaşık 10 dakikalık okuma. +::: + +:::note +**Belirli bir modeli fine-tune etmeye mi çalışıyorsunuz?** Doğrudan [Trainer Seçimi](#/concepts/choosing-trainer) bölümüne atlayın — oradaki karar ağacı sizi doğru konfigürasyona yönlendirir. +::: + +:::note +**Bir deployment'i compliance açısından mı denetliyorsunuz?** [Uyumluluk Genel Bakış](#/compliance/overview) ve [Konfigürasyon Referansı](#/reference/configuration)'na bakın. +::: + +## Bu rehberdeki kullanım kuralları + +- **YAML kod blokları** konfigürasyon dosyanıza koyacağınız hâliyle gösterilir. Kapsamı görebilmek için üst seviye anahtarlar her zaman gösterilir. +- **Shell komutları** istemi belirtmek için `$` ile başlar — kopyalarken `$`'ı dâhil etmeyin. +- **`code`** satır içi metinde bir CLI bayrağına, konfigürasyon anahtarına veya dosya yoluna işaret eder. +- **Callout kutuları** ana akışa sığmayan bilgileri öne çıkarır: + - Note — ek bağlam. + - Tip — önerilen pratik. + - Warning — sık yapılan hata. + - Danger — operasyonel risk; ilerlemeden önce okuyun. + +:::warn +ForgeLM gerçek modeller, gerçek veriler ve gerçek GPU'lar üzerinde çalışır. Yanlış konfigüre edilmiş bir koşu güvenlik eşiklerini geçemeyen, PII sızdıran veya sadece çok GPU saati harcayan bir model üretebilir. Dry-run ve fit-check iş akışları ([İlk Koşunuz](#/getting-started/first-run)) bu sorunları size hiçbir maliyet çıkarmadan yakalamak için var — kullanın. +::: + +## Teknik terimler hakkında bir not + +ForgeLM'in dokümantasyonu teknik terimleri tüm dillerde orijinal hâlinde tutar — `SFT`, `DPO`, `LoRA`, `QLoRA`, `Annex IV`, `GGUF`, `vLLM` vb. Bilinçli bir tercih: bunlar araştırma makalelerinde, kütüphane API'lerinde ve config dosyalarında kullandığınız terimler; çevirmek belirsizlik yaratır. Çevresindeki düz prose tamamen çevrilir. diff --git a/docs/usermanuals/tr/getting-started/project-layout.md b/docs/usermanuals/tr/getting-started/project-layout.md new file mode 100644 index 00000000..6630301c --- /dev/null +++ b/docs/usermanuals/tr/getting-started/project-layout.md @@ -0,0 +1,123 @@ +--- +title: Proje Yapısı +description: ForgeLM diskte config, veri, checkpoint ve artifact'ları nasıl düzenler. +--- + +# Proje Yapısı + +ForgeLM dosyaların *nereye* gideceği konusunda görüş bildirir. Bu, koşuları yeniden üretilebilir, CI/CD hatlarını öngörülebilir ve audit reviewer'ları memnun eder. Bu yapıya birebir uymak zorunda değilsiniz — ama her override için bir flag vardır ve varsayılanlar aşağıdaki konvansiyonları kabul eder. + +## Tipik bir proje ağacı + +```text +my-finetune/ +├── configs/ — YAML konfigürasyon dosyaları +│ ├── customer-support.yaml — trainer config'iniz +│ └── customer-support.dev.yaml — iterasyon için hızlı varyant +├── data/ — JSONL veri setleri +│ ├── train.jsonl +│ ├── validation.jsonl +│ └── preferences.jsonl — DPO/SimPO chosen-rejected çiftleri +├── audit/ — `forgelm audit` çıktısı +│ └── data_audit_report.json +├── checkpoints/ — model çıktıları (gitignored) +│ └── customer-support/ +│ ├── adapter_model.safetensors +│ ├── README.md — model card (Article 13) +│ ├── config_snapshot.yaml — kullanılan config'in dondurulmuş kopyası +│ └── artifacts/ — compliance kanıt paketi +├── ingested/ — `forgelm ingest` üzerinden ham döküman → JSONL +└── .forgelm/ — yerel cache (gitignored) +``` + +## Hangi komut nereye yazar + +| Komut | Yazdığı yer | Notlar | +|---|---|---| +| `forgelm ingest` | `--output` (genelde `data/*.jsonl`) | Ham döküman → SFT-hazır JSONL. | +| `forgelm audit` | `--output` (genelde `audit/`) | PII / sızıntı / kalite raporu. | +| `forgelm --config X.yaml` | YAML'daki `output.dir` | Tüm eğitim artifact'ları. | +| `forgelm export` | `--output` (`.gguf` yolu) | Kuantize tek-dosya model. | +| `forgelm deploy` | `--output` (Modelfile, K8s manifest vb.) | Deployment iskeletleri. | +| `forgelm chat` | hiçbir yere (interaktif) | Terminal'e akıtır. | + +## Neyi commit'lemek, neyi gitignore'a almak + +:::tip +ForgeLM varsayılanları doğru şeyleri commit'leyip gerisini ignore'larsanız version control'la iyi geçinir. +::: + +**Commit:** +- `configs/*.yaml` — koşularınız konfigürasyon; YAML kaynak doğrudur. +- `audit/*.json` — küçük, makine-okunur, PR review'larında faydalı ("audit numaraları geriledi mi?"). +- `checkpoints/*/README.md` ve `checkpoints/*/artifacts/` (model card ve audit paketi, ikisi de küçük). + +**Gitignore:** +- `data/` — genelde fazla büyük; DVC veya tercih ettiğiniz dataset registry'sine alın. +- `checkpoints/*/adapter_model.safetensors` ve diğer ağırlık dosyaları — git için fazla büyük; HuggingFace Hub veya model registry'ye gönderin. +- `ingested/` — ham dokümanlardan yeniden inşa edilebilir. +- `.forgelm/` — yerel cache. + +Başlangıç `.gitignore`: + +```gitignore +# ForgeLM defaults +checkpoints/*/adapter_model.safetensors +checkpoints/*/*.safetensors +checkpoints/*/pytorch_model.bin +checkpoints/*/optimizer.pt +data/ +ingested/ +.forgelm/ +``` + +## Repo konvansiyonları + +| Konvansiyon | Varsayılan | Override | +|---|---|---| +| Config dosyası | `configs/.yaml` | `--config PATH` | +| Audit çıktısı | `./audit/` | `forgelm audit --output PATH` | +| Eğitim çıktısı | `./checkpoints//` | YAML'da `output.dir:` | +| Cache dizini | `~/.forgelm/cache/` | `FORGELM_CACHE_DIR` env var | +| HuggingFace token | `HF_TOKEN` env | YAML'da `auth.hf_token:` | + +## Çoklu config iş akışı + +Çoğu ekip proje başına iki YAML tutar — hızlı iterasyon için bir "dev" config (1 epoch, küçük subset, eval kapalı) ve her kapıyı açan bir "prod" config: + +```text +configs/ +├── customer-support.yaml — tam koşu (release için bunu kullan) +└── customer-support.dev.yaml — dev iterasyon (daha hızlı) +``` + +Dev YAML, prod'unkini `extends:` ile referansta bulunabilir: + +```yaml +# customer-support.dev.yaml +extends: "customer-support.yaml" +training: + epochs: 1 # idi 3 + max_steps: 200 # iterasyonu sınırla +data: + - path: "data/dev/100rows.jsonl" +evaluation: + benchmark: { enabled: false } + safety: { enabled: false } +``` + +Geliştirme sırasında dev varyantı, release için tam olanını koşturun. CI her main merge'inde tam olanını çalıştırır. + +## Compliance artifact'ları nereye gider + +Her başarılı (veya başarısız) eğitim koşusu, [Compliance Genel Bakış](#/compliance/overview) bölümünde anlatılan kanıt paketini içeren bir `checkpoints//artifacts/` dizini oluşturur. Regülatöre veya CI artifact'larında pinleyeceğiniz dizin budur. + +:::warn +**`artifacts/` dizinini koşular arasında birleştirmeyin.** Her koşu ayrı bir kanıt paketidir; karıştırmak SHA-256 manifesti bozar ve tamper-evidence'ı baltalar. +::: + +## Bkz. + +- [Konfigürasyon Referansı](#/reference/configuration) — bu yolları kontrol eden tüm alanlar. +- [CI/CD Hatları](#/operations/cicd) — bu yapıyı GitHub Actions'a bağlamak. +- [Audit Log](#/compliance/audit-log) — artifact dizininin nasıl kullanıldığı. diff --git a/docs/usermanuals/tr/operations/air-gap.md b/docs/usermanuals/tr/operations/air-gap.md new file mode 100644 index 00000000..15b2c21d --- /dev/null +++ b/docs/usermanuals/tr/operations/air-gap.md @@ -0,0 +1,159 @@ +--- +title: Air-Gap Operasyonu +description: İnternet olmadan eğitim ve değerlendirme — her şeyi önceden cache'leyin, izole ağlarda koşturun. +--- + +# Air-Gap Operasyonu + +Regülasyonlu sektörler (savunma, sağlık, bazı finans) ve yüksek-güvenlikli müşteri ortamları için eğitim, internet erişimi olmayan ağlarda gerçekleşmelidir. ForgeLM tamamen air-gap çalışmak üzere tasarlanmıştır: her internet'e dokunan adımın offline eşdeğeri vardır. + +## Online olması gereken (tek sefer) + +Air-gap'e geçmeden önce şunları önceden cache'leyin: + +| Kaynak | Cache yeri | +|---|---| +| Base model | `~/.cache/huggingface/hub/` | +| Tokenizer | (aynı — modelle birlikte) | +| Llama Guard | `~/.cache/huggingface/hub/` | +| `lm-evaluation-harness` görev tanımları | `~/.cache/lm-evaluation-harness/` | +| Python paketleri (`forgelm` + extra'lar) | yerel pip wheel cache | + +Bağlı bir makineden önceden cache'leyin: + +```shell +$ forgelm cache-models \ + --model "Qwen/Qwen2.5-7B-Instruct" \ + --safety "meta-llama/Llama-Guard-3-8B" \ + --output ./airgap-bundle/ + +$ forgelm cache-tasks \ + --tasks hellaswag,arc_easy,truthfulqa,mmlu \ + --output ./airgap-bundle/ +``` + +`airgap-bundle/`'i offline host'a aktarın (USB, scp, ne tür güvenlik politikanız izin veriyorsa). + +## Air-gap host üzerinde + +Yerel cache'i göstermek ve ağ çağrılarını kapatmak için environment variable'lar: + +```shell +$ export HF_HOME="$(pwd)/airgap-bundle/huggingface" +$ export TRANSFORMERS_OFFLINE=1 +$ export HF_HUB_OFFLINE=1 +$ export HF_DATASETS_OFFLINE=1 + +$ forgelm --config configs/run.yaml --offline +``` + +`--offline` bayrağı ForgeLM'e ağ çağrısı yapmamasını söyler. Config'iniz cache'lenmemiş bir modele referans verirse eğitim açık bir hata mesajıyla başarısız olur: + +```text +ERROR: model "meta-llama/Llama-Guard-3-8B" not in local cache. + Bağlı bir makineden önceden cache'leyin: forgelm cache-models --safety meta-llama/Llama-Guard-3-8B +``` + +## `--offline`'ın zorladığı + +| Alt sistem | `--offline` ile davranış | +|---|---| +| HuggingFace Hub indirmeleri | Devre dışı. Model/tokenizer cache'de yoksa hızlı başarısız. | +| W&B / MLflow / Comet | Devre dışı (veya MLflow için file URI ile sadece-yerel). | +| OpenAI / Anthropic judge'lar | Devre dışı. Yerel judge model kullanın. | +| Webhook'lar | Devre dışı (veya `webhook.allow_private` ile iç host'larla sınırlı). | +| Runtime'da pip install | Devre dışı. | +| Telemetry | Yok — ForgeLM zaten asla eve telefon etmez. | + +## Yerel sentetik veri + +Air-gap'te sentetik veri üretimi gerekirse yerel teacher kullanın: + +```yaml +synthetic: + enabled: true + teacher: + provider: "local" + model: "Qwen/Qwen2.5-72B-Instruct" # cache'lenmiş olmalı + load_in_4bit: true +``` + +OpenAI / Anthropic sağlayıcıları `--offline`'da başarısız olur. + +## Yerel LLM-as-judge + +```yaml +evaluation: + judge: + enabled: true + judge_model: + provider: "local" + model: "Qwen/Qwen2.5-72B-Instruct" +``` + +72B yerel judge `gpt-4o-mini`'den yavaş ama kalite tipik kullanım için karşılaştırılabilir. Bkz. [LLM-as-Judge](#/evaluation/judge). + +## Air-gap'te değerlendirme + +`lm-evaluation-harness` genelde görev tanımlarını ve dataset'leri runtime'da indirir. Önceden cache'leyin: + +```shell +$ forgelm cache-tasks --tasks hellaswag,arc_easy,truthfulqa,mmlu +``` + +ForgeLM'i cache kullanacak şekilde konfigüre edin: + +```yaml +evaluation: + benchmark: + tasks_dir: "${HF_HOME}/lm-evaluation-harness/" +``` + +## Air-gap modu doğrulama + +```shell +$ forgelm doctor --offline +ForgeLM 0.5.2 (offline mod doğrulandı) +✓ HF_HUB_OFFLINE ayarlı +✓ TRANSFORMERS_OFFLINE ayarlı +✓ Yerel cache: airgap-bundle/huggingface (3.4 GB cache'li model) +✓ Llama Guard 3 8B yerel olarak mevcut +✓ lm-evaluation-harness: 4 görev cache'li +``` + +`forgelm doctor --offline` herhangi bir şeyin erişilemediğini raporlarsa, air-gap operatörünün vaktini boşa harcamadan *önce* düzeltin. + +## Paket boyutu tahmini + +Tipik bir fine-tuning projesi için: + +| Kaynak | Yaklaşık boyut | +|---|---| +| Base model (7B) safetensors | 14 GB | +| Llama Guard 3 8B | 16 GB | +| Tokenizer + config | <100 MB | +| Eval görev tanımları + cache'li dataset'ler | 500 MB - 2 GB | +| Python wheel'ler (forgelm + extra'lar) | 1-2 GB | +| **Toplam** | **~32-34 GB** | + +Depolamayı buna göre planlayın. + +## Sık hatalar + +:::warn +**Environment variable'ları ayarlamayı unutmak.** `HF_HUB_OFFLINE=1` olmadan HuggingFace kütüphaneleri sessizce eve telefon etmeye çalışıp yerel cache'e fallback yapar. Fallback iyi çalışır ama dışarıya bağlantı yapmış olursunuz — bazı ortamlarda compliance ihlali. +::: + +:::warn +**Önceden cache'lemeden `--offline` kullanmak.** İlk model yüklemesinde eğitim başarısız olur. Eksik kaynakları önden yakalamak için eğitim başlatmadan önce `forgelm doctor --offline` çalıştırın. +::: + +:::tip +**Her şeyi önceden cache'lenmiş bir CI imajı kurun.** Air-gap CI için önceden-cache'li paketi Docker imajına paketleyin. Her CI koşusu cache'lenmiş durumdan başlar. Bkz. [Docker](#/operations/docker). +::: + +## Bkz. + +- [Docker](#/operations/docker) — önceden-cache'li imaj kurma. +- [Kurulum](#/getting-started/installation) — temel kurulum. +- [LLM-as-Judge](#/evaluation/judge) — yerel judge model. diff --git a/docs/usermanuals/tr/operations/cicd.md b/docs/usermanuals/tr/operations/cicd.md new file mode 100644 index 00000000..33c7ac98 --- /dev/null +++ b/docs/usermanuals/tr/operations/cicd.md @@ -0,0 +1,196 @@ +--- +title: CI/CD Hatları +description: ForgeLM'i öngörülebilir exit kodlarıyla GitHub Actions, GitLab CI veya Jenkins'e bağlayın. +--- + +# CI/CD Hatları + +ForgeLM, etkileşimli bir notebook olarak değil, CI/CD hattının bir adımı olarak çalışmak üzere tasarlandı. Her komutun öngörülebilir bir exit kodu, her çıktının yapılandırılmış bir formatı (JSON veya JSONL) ve her kapının net bir verdict'i var — arada gri bölge yok. + +## Exit-kod kontratı + +| Exit | Anlamı | CI ne yapmalı | +|---|---|---| +| `0` | Başarı | Artifact'ları terfi ettir | +| `1` | Konfigürasyon hatası | Hızlıca başarısız ol; YAML'ı düzelt, sonra dene | +| `2` | Audit uyarıları | İncelenmeden merge engellensin | +| `3` | Otomatik geri alma tetiklendi | Başarısız olarak işaretle; gerilemeyi araştır | +| `4` | İnsan onayı bekliyor | Hattı askıya al; reviewer'ı tetikle | + +Tam kontrat için [Exit Kodları](#/reference/exit-codes). + +## GitHub Actions + +Eksiksiz bir hat: + +```yaml +# .github/workflows/train.yml +name: Eğit ve değerlendir + +on: + push: + branches: [main] + paths: + - "configs/**" + - "data/**.jsonl" + workflow_dispatch: + +jobs: + audit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 + with: { python-version: "3.11" } + - run: pip install 'forgelm[ingestion]' + - name: Veri denetimi + run: forgelm audit data/train.jsonl --strict + + train: + needs: audit + runs-on: gpu-runner # CUDA'lı self-hosted + steps: + - uses: actions/checkout@v5 + - run: pip install forgelm + - name: Config doğrula + run: forgelm --config configs/run.yaml --dry-run + - name: VRAM fit-check + run: forgelm --config configs/run.yaml --fit-check + - name: Eğit + run: forgelm --config configs/run.yaml + - name: Artifact'ları yükle + if: always() + uses: actions/upload-artifact@v4 + with: + name: training-artifacts + path: checkpoints/run/artifacts/ +``` + +Artifact upload'taki `if: always()` önemli — başarısızlıkta bile audit log ve kısmi artifact'lar değerli. + +## GitLab CI + +```yaml +# .gitlab-ci.yml +stages: + - audit + - train + +audit: + stage: audit + image: python:3.11 + script: + - pip install 'forgelm[ingestion]' + - forgelm audit data/train.jsonl --strict + +train: + stage: train + tags: [gpu] + script: + - pip install forgelm + - forgelm --config configs/run.yaml --dry-run + - forgelm --config configs/run.yaml --fit-check + - forgelm --config configs/run.yaml + artifacts: + paths: + - checkpoints/run/artifacts/ + when: always +``` + +## Jenkins + +```groovy +pipeline { + agent any + stages { + stage('Audit') { + steps { + sh 'forgelm audit data/train.jsonl --strict' + } + } + stage('Train') { + agent { label 'gpu' } + steps { + sh 'forgelm --config configs/run.yaml --dry-run' + sh 'forgelm --config configs/run.yaml --fit-check' + sh 'forgelm --config configs/run.yaml' + } + post { + always { + archiveArtifacts artifacts: 'checkpoints/run/artifacts/**' + } + } + } + } +} +``` + +## JSON çıktı modu + +Koşu çıktısının programatik parse'ı için `--output-format json` kullanın: + +```shell +$ forgelm --config configs/run.yaml --output-format json | jq '.verdict' +"success" +``` + +ForgeLM'in stderr'a yazdığı her olay stdout'ta da JSON nesnesi olarak çıkar — log aggregator'ınıza veya dashboard'unuza pipe'lamaya hazır. + +## Model cache + +Model indirme taze CI koşusunun en yavaş kısmıdır. Cache'leyin: + +```yaml +# GitHub Actions +- uses: actions/cache@v4 + with: + path: ~/.cache/huggingface + key: hf-${{ runner.os }}-${{ hashFiles('configs/**.yaml') }} +``` + +Çoklu-runner kurulumunda cache'i paylaşımlı depolamaya (S3, NFS) yönlendirin; tüm runner'lar paylaşır. + +## Eşzamanlılık kontrolü + +Çoğu proje eğitimi paralel değil seri koşturur — aynı GPU'da paralel iş OOM'a yol açar. Concurrency kullanın: + +```yaml +# GitHub Actions +concurrency: + group: training-${{ github.ref }} + cancel-in-progress: false # iptal etme; sıraya al +``` + +## Self-hosted GPU runner'ları + +GitHub Actions için self-hosted GPU: + +1. GitHub runner'ı GPU host'a kurun. +2. Etiketleyin: `self-hosted, linux, x64, gpu`. +3. Job'ta referans verin: `runs-on: [self-hosted, gpu]`. + +ForgeLM, runner'ı CUDA, Python ve önceden kurulu extra'larla kurmak için bir `Dockerfile.runner` referansı yayınlar. + +## Sık hatalar + +:::warn +**Exit kodları bastırmak.** `forgelm ... || true` kapı kontratının tüm amacını yok eder. Gerçekten devam etmeniz gerekiyorsa exit koduna göre dallanın. +::: + +:::warn +**Audit ve eğitimi aynı runner'da çalıştırmak.** Audit CPU-only; eğitim GPU ister. Önce ucuz runner'da audit çalıştırın, audit geçerse pahalı GPU runner'da eğitin. Veride bug olduğunda GPU zamanı boşa harcanmaz. +::: + +:::warn +**Başarısızlıkta artifact yüklememek.** Bir koşu başarısız olduğunda audit log en değerli kanıttır. Her zaman artifact upload'lara `if: always()` (GitHub) / `when: always` (GitLab) koyun. +::: + +:::tip +Gece eğitimleri için otomatik geri alma + Slack webhook konfigüre edin. Sabah ya terfi etmiş bir modele ya da net bir olay raporuna uyanırsınız — asla "bilmiyorum, sabah 3'te bozuldu" gizemine değil. +::: + +## Bkz. + +- [Exit Kodları](#/reference/exit-codes) — CI'nın dayandığı kontrat. +- [Webhook'lar](#/operations/webhooks) — Slack/Teams bildirimleri. +- [Otomatik Geri Alma](#/evaluation/auto-revert) — exit 3'ü tetikleyen. diff --git a/docs/usermanuals/tr/operations/docker.md b/docs/usermanuals/tr/operations/docker.md new file mode 100644 index 00000000..08a62f54 --- /dev/null +++ b/docs/usermanuals/tr/operations/docker.md @@ -0,0 +1,149 @@ +--- +title: Docker +description: Yerel, on-prem ve cloud arası yeniden üretilebilir koşular — aynı imaj, aynı davranış. +--- + +# Docker + +ForgeLM, yerel geliştirme, on-prem cluster ve cloud GPU'lar arası yeniden üretilebilir eğitim koşuları için resmi bir Dockerfile ve `docker-compose.yml` yayınlar. + +## Hızlı başlangıç + +Resmi imajı çekin: + +```shell +$ docker pull ghcr.io/cemililik/forgelm:latest +$ docker run --gpus all \ + -v $PWD:/workspace \ + -v $HOME/.cache/huggingface:/root/.cache/huggingface \ + -e HF_TOKEN \ + ghcr.io/cemililik/forgelm:latest \ + forgelm --config /workspace/configs/run.yaml +``` + +`--gpus all` host'ta NVIDIA Container Toolkit ister. Projenizi `/workspace` olarak ve HuggingFace cache'ini mount edin; model indirmeleri koşular arası kalıcı olur. + +## İmaj varyantları + +| Tag | İçerir | Boyut | +|---|---|---| +| `latest` | Base + tüm extra'lar (ingestion, scale, export, deepspeed) | ~12 GB | +| `slim` | Sadece base — extra yok | ~6 GB | +| `airgap` | Base + extra'lar + önceden-cache'li Qwen 2.5 7B + Llama Guard | ~30 GB | + +Çoğu ekip için `latest` doğru tercih. Air-gap deployment'ları için `airgap`'ten türeyen, kendi spesifik modellerinizi içeren özel imaj kurun. Bkz. [Air-Gap Operasyonu](#/operations/air-gap). + +## docker-compose + +Çoklu-servis yerel geliştirme (eğitim + deney takibi + webhook receiver) için: + +```yaml +# docker-compose.yml +version: "3.9" + +services: + trainer: + image: ghcr.io/cemililik/forgelm:latest + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] + volumes: + - .:/workspace + - hf-cache:/root/.cache/huggingface + environment: + - HF_TOKEN + - WANDB_API_KEY + - SLACK_WEBHOOK + command: forgelm --config /workspace/configs/run.yaml + + mlflow: + image: ghcr.io/mlflow/mlflow:latest + ports: + - "5000:5000" + volumes: + - ./mlruns:/mlflow/mlruns + command: mlflow server --host 0.0.0.0 --port 5000 + +volumes: + hf-cache: {} +``` + +```shell +$ docker compose up trainer +``` + +## Kaynaktan build + +Özel modifikasyonlar gerekirse: + +```shell +$ git clone https://github.com/cemililik/ForgeLM +$ cd ForgeLM +$ docker build -t forgelm:custom -f Dockerfile . +$ docker run --gpus all forgelm:custom forgelm --version +``` + +Dockerfile çok-aşamalı: builder aşaması ağır bağımlılıkları (CUDA, PyTorch, bitsandbytes) kurar, sonra runtime aşaması derlenmiş artifact'ları kopyalar. Toplam build süresi: hızlı bağlantıda ~15 dakika. + +## Air-gap imajı + +Air-gap ortamlar için her şey önceden cache'lenmiş imaj kurun: + +```dockerfile +# airgap.Dockerfile +FROM ghcr.io/cemililik/forgelm:latest + +# Base modeli önceden cache'le +RUN forgelm cache-models --model "Qwen/Qwen2.5-7B-Instruct" + +# Llama Guard'ı önceden cache'le +RUN forgelm cache-models --safety "meta-llama/Llama-Guard-3-8B" + +# Eval görevlerini önceden cache'le +RUN forgelm cache-tasks --tasks hellaswag,arc_easy,truthfulqa,mmlu + +# Konteynerda offline modu zorla +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 +ENV HF_DATASETS_OFFLINE=1 + +ENTRYPOINT ["forgelm"] +CMD ["--help"] +``` + +Build, kaydet, aktar: + +```shell +$ docker build -t forgelm-airgap -f airgap.Dockerfile . +$ docker save forgelm-airgap | gzip > forgelm-airgap.tar.gz +# forgelm-airgap.tar.gz'ı air-gap host'a aktar +$ docker load < forgelm-airgap.tar.gz +``` + +## Sık hatalar + +:::warn +**`--gpus all`'i unutmak.** Bu olmadan konteyner GPU'nuzu göremez ve ForgeLM CPU'ya fallback yapar — 7B modeli CPU'da eğitmek imkânsız. +::: + +:::warn +**HuggingFace cache'ini mount etmemek.** Her konteyner başlangıcında base model (15+ GB) yeniden indirilir. İndirmelerin kalıcı olması için `~/.cache/huggingface`'i her zaman mount edin. +::: + +:::warn +**Dockerfile'da hardcoded API key'ler.** Build arg'ları imaj layer geçmişine gömülür. Bunun yerine runtime environment variable kullanın: `docker run -e HF_TOKEN ...`. +::: + +:::tip +Kubernetes deployment'ları için aynı imajı GPU node'larına işaret eden custom resource definition'la kullanın. ForgeLM'in davranışı aynı — sadece orkestrasyon katmanı değişir. +::: + +## Bkz. + +- [Air-Gap Operasyonu](#/operations/air-gap) — tam offline deployment. +- [CI/CD Hatları](#/operations/cicd) — imajı GitHub Actions'da kullanmak. +- [Kurulum](#/getting-started/installation) — Docker dışı kurulum. diff --git a/docs/usermanuals/tr/operations/experiment-tracking.md b/docs/usermanuals/tr/operations/experiment-tracking.md new file mode 100644 index 00000000..e326ae53 --- /dev/null +++ b/docs/usermanuals/tr/operations/experiment-tracking.md @@ -0,0 +1,143 @@ +--- +title: Deney Takibi +description: report_to ayarı üzerinden W&B, MLflow ve TensorBoard entegrasyonu. +--- + +# Deney Takibi + +ForgeLM deney takibini yeniden icat etmez — ekibinizin zaten kullandığı şeye `training.report_to` alanı üzerinden entegre olur. W&B, MLflow, TensorBoard ve Comet ML birinci-sınıf desteklenir. + +## Hızlı örnek + +```yaml +training: + trainer: "sft" + report_to: ["wandb", "tensorboard"] # aynı anda ikisi + run_name: "customer-support-v1.2.0" + tags: ["dpo", "qlora", "tr"] +``` + +ForgeLM her konfigüre backend'e loss, learning rate, eval metrikleri ve benchmark puanları akıtır. + +## Desteklenen backend'ler + +### Weights & Biases (W&B) + +```yaml +training: + report_to: ["wandb"] + wandb: + project: "forgelm-customer-support" + entity: "acme-ml" + api_key: "${WANDB_API_KEY}" + log_artifacts: true # W&B'a checkpoint yükle +``` + +Auth: `WANDB_API_KEY` environment variable'ını ayarlayın veya eğitim host'unda bir kez `wandb login` çalıştırın. + +### MLflow + +```yaml +training: + report_to: ["mlflow"] + mlflow: + tracking_uri: "http://mlflow.internal:5000" + experiment_name: "customer-support" + registry_uri: "http://mlflow.internal:5000" + log_model: true # MLflow Model Registry'e terfi +``` + +Auth: standart MLflow env var'ları (`MLFLOW_TRACKING_USERNAME`, `MLFLOW_TRACKING_PASSWORD` veya token). + +### TensorBoard + +```yaml +training: + report_to: ["tensorboard"] + tensorboard: + log_dir: "${output.dir}/tensorboard" +``` + +Dış servis gerekmez — log dosyaları yereldir. + +### Comet ML + +```yaml +training: + report_to: ["comet_ml"] + comet_ml: + api_key: "${COMET_API_KEY}" + project_name: "forgelm-customer-support" +``` + +## Loglanan şeyler + +| Metrik | Ne zaman | +|---|---| +| `train/loss` | Her adım | +| `train/lr` | Her adım | +| `train/grad_norm` | Her adım (`log_grad_norm: true` ise) | +| `eval/loss` | Her eval aralığı | +| `benchmark/` | Koşu başına bir kez (eval sonrası) | +| `safety//max` | Koşu başına bir kez (güvenlik eval sonrası) | +| `safety//mean` | Koşu başına bir kez | +| `system/gpu_utilization` | Her 30s'de örneklenir | +| `system/vram_used_gb` | Her 30s'de örneklenir | + +## Koşu adlandırma ve etiketler + +```yaml +training: + run_name: "customer-support-{config_hash}" # interpolasyon destekli + tags: ["dpo", "qlora", "tr", "v1.2"] + notes: "truthfulqa floor'unu yakalamak için beta 0.1'den 0.15'e çıkarıldı" +``` + +`notes` alanı, prose annotasyonu destekleyen her backend'de kaydedilir. + +## Artifact yönetimi + +W&B ve MLflow için ForgeLM checkpoint'i ve audit paketini artifact olarak yükleyebilir: + +```yaml +training: + wandb: + log_artifacts: true # tam checkpoint + paket + artifact_type: "model" +``` + +Çok büyük checkpoint'ler için W&B/MLflow artifact store'larından çok model registry (HuggingFace Hub) tercih edin. Free tier'lar küçük boyutlarda sınırlanır. + +## Koşu karşılaştırma + +Her backend'in UI'sı karşılaştırmayı doğal şekilde halleder — karşılaştırılabilir koşular `run_name` öneki, etiketler ve config hash paylaşır. ForgeLM CLI'sı da yardım eder: + +```shell +$ forgelm compare-runs runs/v1.0 runs/v1.1 runs/v1.2 + v1.0 v1.1 v1.2 +hellaswag 0.612 0.617 0.621 +truthfulqa 0.480 0.482 0.475 ↓ +S5_max 0.041 0.038 0.082 ↑↑ +loss 1.43 1.39 1.35 +``` + +Oklar otomatik türetilir: anlamlı iyileşme yeşil, regresyon kırmızı. + +## Sık hatalar + +:::warn +**API key'leri hardcoded yapmak.** W&B / MLflow / Comet key'lerini doğrudan YAML'a koymayın. Her zaman `${ENV_VAR}` interpolasyonu kullanın. Sırların dump'lanmış config'e dahil olmadığını teyit etmek için `audit_log.jsonl`'a bakın. +::: + +:::warn +**Erişilemeyen backend'lere raporlama.** `wandb.ai` çalışmıyorsa veya firewall'unuz engelliyorsa ForgeLM uyarı bırakır ama eğitimi başarısız etmez. Uyarıları izleyin; aksi halde hiçbir şeyin loglanmadığını kaçırabilirsiniz. +::: + +:::tip +**Birden çok backend paralel kullanın.** Bir koşu sırasında lokal debugging için TensorBoard, sonradan ekipler-arası işbirliği için W&B. İkisini de konfigüre edin — ekstra maliyet yok. +::: + +## Bkz. + +- [Konfigürasyon Referansı](#/reference/configuration) — tam `report_to` ve backend ayarları. +- [JSON Çıktı Modu](#/operations/cicd) — kendi takibinize log'ları pipe etmek için. diff --git a/docs/usermanuals/tr/operations/gpu-cost.md b/docs/usermanuals/tr/operations/gpu-cost.md new file mode 100644 index 00000000..e3f36df1 --- /dev/null +++ b/docs/usermanuals/tr/operations/gpu-cost.md @@ -0,0 +1,143 @@ +--- +title: GPU Maliyet Tahmini +description: 18 GPU profilinde otomatik tespit ve saatlik tarifenize göre koşu başı maliyet izleme. +--- + +# GPU Maliyet Tahmini + +ForgeLM, üzerinde koştuğunuz GPU'yu tespit eder, profilini (bellek, compute, tipik saatlik tarife) bulur ve koşu başı maliyeti izler. Her koşunun ardından audit log tam olarak ne kadar GPU zamanı kullanıldığını ve maliyetini kaydeder. + +## Tespit nasıl çalışır + +Başlangıçta `forgelm` şunları okur: +- Donanım tanımlama için `nvidia-smi --query-gpu=name,memory.total,...`. +- `forgelm/gpu_profiles.yaml`'dan eşleşen profil. + +Desteklenen GPU'lar: + +| Sınıf | Modeller | +|---|---| +| Datacenter | A100 40 GB / 80 GB, H100 80 GB, H200, L40S | +| Workstation | RTX 6000 Ada, RTX A6000 | +| Consumer | RTX 4090, RTX 4080, RTX 3090, RTX 3080 | +| Sadece-cloud | T4, V100, A10G | +| Apple | M1/M2/M3 Max (CPU/MPS fallback) | + +GPU'nuz tanınmazsa ForgeLM uyarı bırakır ve generic profile fallback yapar (maliyet tahmini yok ama eğitim çalışır). + +## Saatlik tarife konfigürasyonu + +```yaml +output: + cost_tracking: + enabled: true + rate_per_hour: + A100_80GB: 1.10 # saatlik USD + A100_40GB: 0.85 + H100_80GB: 2.40 + RTX_4090: 0.50 # kabaca elektrik maliyeti + default: 1.00 # eşleşmeyen GPU'lar için + currency: "USD" +``` + +Bunu proje başına bir kez ayarlayın. ForgeLM maliyet raporlama için eşleşen tarifeyi kullanır. + +## Çıktı + +Her koşunun ardından audit log şunları kaydeder: + +```json +{ + "event": "run_complete", + "ts": "2026-04-29T14:33:10Z", + "duration_seconds": 1892, + "gpu_profile": "A100_80GB", + "gpus_used": 1, + "estimated_cost_usd": 0.578, + "rate_per_hour": 1.10, + "currency": "USD" +} +``` + +Model card atıf yapar: + +```markdown +## Eğitim maliyeti + +Bu model 1× A100 80GB üzerinde 31m 32s eğitildi, +konfigüre tarifeyle tahmini $0.58 USD. +``` + +## Uçuş öncesi maliyet tahmini + +Uzun bir eğitim koşusu başlatmadan önce tahmin alın: + +```shell +$ forgelm --config configs/run.yaml --estimate-cost +Tahmini eğitim süresi: 6h 30m +Tahmini maliyet (1× A100 80GB, $1.10/sa): $7.15 +``` + +Tahmin küçük kalibrasyon koşusundan dataset boyutu + epoch + adım başı throughput kullanır. Doğruluk genelde gerçeğin %20 içinde. + +## Çoklu-GPU ve dağıtık + +Çoklu-GPU eğitiminde ForgeLM GPU başı tarifeyi GPU sayısıyla çarpar: + +```yaml +output: + cost_tracking: + rate_per_hour: + A100_80GB: 1.10 +``` + +4×A100 koşusu 2 saat = 4 × 2 × $1.10 = $8.80; ZeRO veya FSDP kullanmak fark etmez. + +## Maliyet uyarıları + +Kontrolden çıkabilecek koşular için: + +```yaml +output: + cost_tracking: + alert_threshold_usd: 50.0 # geçildiğinde webhook fırlat + halt_threshold_usd: 200.0 # eğitim durur +``` + +Uyarı konfigüre webhook'u fırlatır (bkz. [Webhook'lar](#/operations/webhooks)) — yanlış konfigüre koşunun gece bütçeyi haftalık bitirmesini CI'da yakalamak için faydalı. + +## Özel GPU profilleri + +Varsayılan profilde olmayan GPU eklemek için: + +```yaml +gpu_profiles: + custom: + - name: "AcmeNVIDIA-XYZ" + pattern: "AcmeNVIDIA-XYZ" # nvidia-smi name'ye karşı eşleştir + memory_gb: 96 + compute_capability: 9.0 + tensor_cores: true +``` + +Bunu proje kökünüze `gpu_profiles.local.yaml` olarak bırakın; ForgeLM otomatik birleştirir. + +## Sık hatalar + +:::warn +**Saatlik tarifeyi mutlak doğru saymak.** ForgeLM'in varsayılanları makul ortalamalar — gerçek cloud faturanız instance tipi, bölge, spot vs on-demand ve indirimlerinize bağlı. Kendi gerçek tarifenizle override edin. +::: + +:::warn +**Paylaşımlı GPU'larda multi-tenancy.** Birden çok iş bir GPU'yu paylaşıyorsa (eğitimde nadir, inference'ta yaygın), maliyet izleme bölmek yerine çarpıyor. Gerçek tahsisi belirtmek için `--gpus N` kullanın. +::: + +:::tip +**Maliyeti zaman içinde izleyin.** Audit log her koşunun maliyetini içerir; haftalar boyunca trend alın, sürünen aşımları yakalayın. Aynı eğitim süresinde 2× maliyet artışı genelde verinin büyüdüğü veya hyperparam'ların kaydığı işaretidir. +::: + +## Bkz. + +- [VRAM Fit-Check](#/operations/vram-fit-check) — maliyet tahmini ile birlikte koşar. +- [CI/CD Hatları](#/operations/cicd) — CI'da maliyet uyarıları. +- [Konfigürasyon Referansı](#/reference/configuration) — tam `cost_tracking` bloğu. diff --git a/docs/usermanuals/tr/operations/troubleshooting.md b/docs/usermanuals/tr/operations/troubleshooting.md new file mode 100644 index 00000000..aa459a75 --- /dev/null +++ b/docs/usermanuals/tr/operations/troubleshooting.md @@ -0,0 +1,181 @@ +--- +title: Sorun Giderme +description: Sık karşılaşılan ForgeLM hataları ve çözümleri. +--- + +# Sorun Giderme + +Bu sayfa en sık karşılaşılan ForgeLM hatalarını ve işe yarayan çözümleri listeler. Listede olmayan herhangi bir şey için önce `forgelm doctor` çalıştırın — ortam sorunlarının %80'ini yakalar. + +## Kurulum sorunları + +### macOS'ta `bitsandbytes` import hatası + +```text +ImportError: bitsandbytes/libbitsandbytes_cpu.so: cannot find ... +``` + +**Sebep:** `bitsandbytes` Metal/MPS desteklemiyor. macOS host'ları 4-bit kuantize eğitim (QLoRA) çalıştıramaz. + +**Çözüm:** Ya CUDA'lı bir Linux'ta koşturun ya da full precision'da eğitin (`model.load_in_4bit: false`). + +### `undefined symbol: __cudaRegisterFatBinaryEnd` + +**Sebep:** PyTorch ve CUDA toolkit sürümleri uyumsuz. + +**Çözüm:** PyTorch'u CUDA sürümünüzle eşleşecek şekilde tekrar kurun: + +```shell +$ pip uninstall torch torchvision torchaudio +$ pip install torch --index-url https://download.pytorch.org/whl/cu121 # CUDA sürümünüzü yazın +``` + +### `OSError: HuggingFace token not found` + +**Sebep:** Bazı modeller (Llama, Llama Guard) geçit kontrollü ve auth token ister. + +**Çözüm:** `huggingface-cli login` çalıştırın veya `HF_TOKEN` environment variable ayarlayın. ForgeLM ikisini de okur. + +## Eğitim sorunları + +### Loss NaN'a gidiyor + +```text +[2026-04-29 14:18:55] training_step_complete loss=nan +``` + +**Sebepler (en sık başta):** +1. Learning rate çok yüksek (özellikle full FT'de — 1e-5 deneyin). +2. Çok düşük precision'da (fp16) gradient overflow. bfloat16'ya geçin: `model.bnb_4bit_compute_dtype: "bfloat16"`. +3. Aşırı token'lı bozuk veri satırı (`forgelm audit` koşturun, kalite flag'lerine bakın). +4. Inf/NaN döndüren özel reward fonksiyonu (sadece GRPO). + +### Train'de loss düşüyor, eval'de artıyor + +**Sebep:** Overfitting; özellikle küçük dataset ve çok epoch'la. + +**Çözüm:** +- `epochs`'u azaltın (10 değil, 1-3 ile başlayın). +- Embedding regülarizasyonu için `neftune_noise_alpha: 5.0` ekleyin. +- Learning rate'i düşürün. +- Daha çeşitli eğitim verisi ekleyin. + +### Eğitim adım 0'da çöküyor + +**Sebep:** Neredeyse her zaman `--dry-run`'ın yakaladığı bir konfigürasyon problemi. + +**Çözüm:** Eğitimden önce her zaman `forgelm --config X.yaml --dry-run` koşturun. "Eğitim çöktü" raporlarının %90'ı atlanmış dry-run'lara dayanır. + +### Eğitim beklenenden çok yavaş + +**Sebepler (en sık başta):** +1. Desteklenen modelde Unsloth kullanılmaması (Qwen / Llama / Mistral için `model.use_unsloth: true`). +2. Talimat verisinde `packing: false` (true yapmak %30-50 throughput sağlar). +3. Yanlışlıkla CPU offload açık (`distributed.cpu_offload: false`). +4. Mixed-precision yanlış konfigüre (`bfloat16` kullanın, `float16` değil). +5. Disk I/O bağımlı — dataset'iniz yavaş depolamada. + +Eğitim sırasında `nvidia-smi`: GPU kullanımı %85+ olmalı. %50'nin altındaysa GPU değil CPU veya I/O bağımlısınız. + +## OOM hataları + +### Eğitim ortasında `CUDA out of memory` + +**Sebep:** Özellikle uzun bir dizinin yarattığı activation bellek patlaması. + +**Çözüm:** +- Peak tahminini doğrulamak için `--fit-check` koşturun. +- Verinizde uzun aykırı değerler varsa `max_length`'i düşürün. +- `packing: true` etkinleştirin (dizi uzunluğunu eşitler). +- `batch_size`'ı düşürüp `gradient_accumulation_steps`'i artırın (aynı etkili batch, daha az peak). + +### Eğitimde değil eval'de OOM + +**Sebep:** Eval genelde sliding-window veya packing olmadan koşar — peak eğitim peak'ini aşabilir. + +**Çözüm:** Eval `max_length`'ini eğitiminkinden düşük ayarlayın: + +```yaml +evaluation: + max_length: 4096 # eğitim 32K'da, eval 4K'da +``` + +## Veri sorunları + +### `audit refuses to certify a leaky split` + +**Sebep:** Train satırları val veya test'te de görünüyor (`cross_split_overlap > 0`). + +**Çözüm:** Verinizi tekrar bölün; tek bir dökümanın birden çok split'e yayılmadığından emin olun. Bkz. [Split-arası Sızıntı](#/data/leakage). + +### Audit çok fazla kalite flag'i raporluyor + +**Sebep:** Kalite filtresi varsayılan olarak muhafazakar, ama kod veya simge-ağırlıklı veride aşırı flag verebilir. + +**Çözüm:** YAML'da belirli kontrolleri devre dışı bırakın: + +```yaml +audit: + quality_filter: + skip: ["min_alpha_ratio", "max_bullet_ratio"] +``` + +### Format otomatik algılaması yanlış + +**Sebep:** JSONL'in ilk satırı diğer satırlarla eşleşmiyor. + +**Çözüm:** Formatı açıkça ayarlayın: `format: "preference"` (ya da hangisiyse). + +## Eval / güvenlik sorunları + +### Llama Guard her zaman "high severity" raporluyor + +**Sebep:** Probe seti, base modelin de zaten geçemediği adversarial girdiler içeriyor. Llama Guard hem base'i hem fine-tuned çıktıları doğru şekilde flagliyor. + +**Çözüm:** Bu doğru davranış. Önemli olan kontrol *baseline'a karşı gerileme*, mutlak puan değil. `evaluation.safety.baseline`'ın pre-train baseline'ına işaret ettiğinden emin olun. + +### Benchmark puanları kamuya açık sonuçlardan çok farklı + +**Sebep:** Muhtemelen yayınlanan leaderboard kuralıyla `num_fewshot` uyuşmazlığı. + +**Çözüm:** Her görevin kanonik ayarını kontrol edin (ör. MMLU kanonik olarak 5-shot) ve eşleştirin. + +## Compliance sorunları + +### `audit_log.jsonl chain hash invalid` + +**Sebep:** Audit log değiştirilmiş (veya dosya sistemi bozmuş). + +**Çözüm:** Log'u değiştirmeyin. Bozulma olduysa orijinal artifact'lar artık güvenilir değildir — temiz durumdan eğitimi yeniden koşturun. + +### Annex IV gerekli alanları eksik + +**Sebep:** YAML'da gerekli `compliance:` alanları ayarlanmamış. + +**Çözüm:** `forgelm verify-annex-iv path/to/annex_iv.json` ile eksik alan listesini alın. + +## Webhook'lar fırlamıyor + +**Sebepler:** +- Webhook URL özel IP'ye işaret ediyor ve `webhook.allow_private` false. +- TLS sertifika doğrulaması başarısız. +- Endpoint 4xx döndürüyor (varsayılan log'da sessiz). + +**Çözüm:** `audit_log.jsonl` içinde `webhook_failed` olaylarına bakın; yanıt durumu ve gövdeyi içerirler. + +## Bug bildirimi nereye + +`forgelm doctor` her şeyin iyi olduğunu söylediği halde sorun devam ediyorsa toplayın: + +1. Başarısız olan tam `forgelm` komutu. +2. Tam hata çıktısı. +3. `config.yaml`'iniz (sırlar redakte edilmiş). +4. `forgelm doctor` çıktısı. + +Issue açın: . Maintainer ekibi 48 saat içinde triaj eder. + +## Bkz. + +- [`forgelm doctor`](#/getting-started/installation) — birinci-hat tanı. +- [VRAM Fit-Check](#/operations/vram-fit-check) — uçuş öncesi bellek kontrolü. +- [Konfigürasyon Referansı](#/reference/configuration) — her YAML alanı. diff --git a/docs/usermanuals/tr/operations/vram-fit-check.md b/docs/usermanuals/tr/operations/vram-fit-check.md new file mode 100644 index 00000000..9031c7d6 --- /dev/null +++ b/docs/usermanuals/tr/operations/vram-fit-check.md @@ -0,0 +1,142 @@ +--- +title: VRAM Fit-Check +description: Uçuş öncesi bellek tahmini — uzun bir iş başlatmadan önce fits, tight, OOM veya unknown. +--- + +# VRAM Fit-Check + +`--fit-check` config'inizin statik analizini yapar ve peak VRAM'in mevcut GPU'ya sığıp sığmayacağını raporlar. Eğitim olmaz, veri yüklenmez — sadece "OOM olur mu?" sorusunu saniyeler içinde cevaplar. + +## Hızlı örnek + +```shell +$ forgelm --config configs/customer-support.yaml --fit-check +FITS est. peak 11.4 GB / 12 GB available + +Bileşenler: + Model ağırlıkları (4-bit): 3.8 GB + KV cache (max_length=4096): 1.4 GB + Activations (batch=2): 2.6 GB + Optimizer state (LoRA): 1.3 GB + Referans model (DPO): 1.9 GB ← QLoRA olmadan OOM olurdu + Buffer (%10): 0.4 GB + ------- + Toplam tahmini peak: 11.4 GB + +Öneriler: yok — bu konfigürasyon sığar. +``` + +## Verdict'ler + +| Verdict | Anlamı | Aksiyon | +|---|---|---| +| `FITS` | VRAM rahat içinde. | Devam edin. | +| `TIGHT` | VRAM içinde ama activation patlamaları için pay yok. | `max_length`'i veya batch size'ı düşürün. | +| `OOM` | Sığmayacak. | Önerilen düzeltmeleri uygulayın. | +| `UNKNOWN` | GPU profil veritabanında değil. | Muhafazakar koşun; GitHub Issues'a bildirin. | + +## `OOM` neye benzer + +```text +$ forgelm --config configs/large-context.yaml --fit-check +OOM est. peak 32.4 GB / 24 GB available + +Bileşenler: + Model ağırlıkları (full prec): 14.2 GB + KV cache (max_length=32768): 6.8 GB ← en büyük katkı + ... + +Önerilen düzeltmeler (genelde herhangi biri çözer): + 1. QLoRA aç: model.load_in_4bit: true (~10 GB tasarruf) + 2. max_length düşür: 32768 → 8192 (~5 GB tasarruf) + 3. batch_size düşür: 4 → 2 (~2 GB tasarruf) + 4. DPO yerine SimPO (referans yok) (~10 GB tasarruf) + 5. distributed.zero_stage: 2 aç (multi-GPU) +``` + +## Tahmin edilen bileşenler + +| Bileşen | Bağımlı | +|---|---| +| Model ağırlıkları | Model boyutu + precision (full / 8-bit / 4-bit) | +| KV cache | `max_length` × hidden dim × layer × head | +| Activations | `batch_size` × `max_length` × hidden dim | +| Gradients | Model boyutu × precision (veya PEFT ise LoRA rank) | +| Optimizer state | Adam: 2× model boyutu × precision; LoRA: 2× rank × ... | +| Referans model | Sadece DPO/KTO — modelin tam kopyası | +| Reward model | Sadece GRPO | +| Activation peak | Mimari-özgü pattern'lerden tahmin | +| Buffer | %10 güvenlik payı | + +## Ne kadar doğru + +Empirik olarak, `--fit-check` zamanın ~%95'inde doğru. %5 başarısızlık genelde: + +- Olağandışı model mimarileri (sparse expert routing'li MoE). +- Çok yüksek token verimliliğiyle sample packing (beklenenden iyi). +- DeepSpeed offload konfigürasyonları (beklenenden düşük). + +Sınırda durumlarda gönül rahatlığı için verdict güven aralığıyla tahmin gösterir: + +```text +TIGHT est. peak 21.8 GB / 24 GB (%95 güven: 19.4 - 23.9 GB) +``` + +Güven aralığının üst sınırı mevcut VRAM'i aşıyorsa OOM-olası muamelesi yapın. + +## Çoklu-GPU + +Dağıtık eğitim için fit-check sharding'i hesaba katar: + +```shell +$ forgelm --config configs/zero3.yaml --fit-check --gpus 4 +FITS est. peak 14.2 GB / 80 GB GPU başına (4'e shardlı) + +ZeRO-3 sharding: + Optimizer state: GPU başına 1/4 + Gradients: GPU başına 1/4 + Parameters: GPU başına 1/4 +``` + +## Programatik API + +Dashboard veya otomasyon için: + +```python +from forgelm.fit_check import estimate_peak_memory, available_memory + +estimate = estimate_peak_memory(config_path="configs/run.yaml") +available = available_memory() +print(f"Verdict: {estimate.verdict}") +print(f"Peak: {estimate.peak_gb:.1f} GB / {available.total_gb:.1f} GB available") +``` + +## --fit-check'in yanıldığı yerler + +Uç durumlar: + +- **Olağandışı MoE routing.** Bazı MoE modellerinin yük desenleri tahminci tarafından modellenmiyor. Kısa kalibrasyon eğitimi koşturup gerçek peak'i karşılaştırın. +- **CPU offload.** `offload_param: cpu` ile ZeRO-3 VRAM'i öngörülemeyecek şekilde düşürür; tahmin muhafazakar (VRAM kullanımını fazla tahmin eder). +- **Çok uzun diziler** (>64K). `O(N²)` attention terimi baskın; uygulamadaki küçük farklar önemli. + +Bu durumlar için `--fit-check-strict` kullanın; en kötü durum tahminini kullanır ve median tahmin `FITS` derken bile `TIGHT` raporlar. + +## Sık hatalar + +:::warn +**"Sanırım sığar" koşularda fit-check'i atlamak.** 5 dakikalık fit-check, eğitime 6 saat kala 6 saatlik OOM'dan sizi kurtarır. Her zaman koşturun. +::: + +:::warn +**`TIGHT` verdict'iyle koşturmak.** Tight koşular aralıklı OOM verir — ilk birkaç epoch sığar, sonra özellikle uzun bir dizi activation patlaması tetikler. Ya bir şeyi düşürün ya da çökme için hazır olun. +::: + +:::tip +**--dry-run'dan önce fit-check.** Sıra önemli: dry-run modeli indirir (yavaş); fit-check statik analiz (hızlı). Fit-check OOM derse indirmeden tasarruf etmiş olursunuz. Her zaman önce fit-check. +::: + +## Bkz. + +- [GPU Maliyet Tahmini](#/operations/gpu-cost) — kardeş uçuş öncesi kontrol. +- [Dağıtık Eğitim](#/training/distributed) — tek GPU OOM olduğunda. +- [LoRA, QLoRA, DoRA](#/training/lora) — yaygın OOM çaresi. diff --git a/docs/usermanuals/tr/operations/webhooks.md b/docs/usermanuals/tr/operations/webhooks.md new file mode 100644 index 00000000..1cc2e88a --- /dev/null +++ b/docs/usermanuals/tr/operations/webhooks.md @@ -0,0 +1,159 @@ +--- +title: Webhook'lar +description: Eğitim olaylarında Slack ve Teams bildirimleri — başlangıç, başarı, hata, otomatik geri alma. +--- + +# Webhook'lar + +ForgeLM eğitim dönüm noktalarında yapılandırılmış webhook fırlatır. Bunları Slack, Teams veya JSON payload kabul eden herhangi bir incident aracına bağlayın — hiç kimsenin log izlemesine gerek kalmadan doğru bağlamı doğru insanlara getirin. + +## Hızlı örnek + +```yaml +output: + webhook: + url: "${SLACK_WEBHOOK}" + events: ["run_start", "auto_revert", "run_complete", "run_failed"] + template: "slack" # veya teams, generic +``` + +ForgeLM `${SLACK_WEBHOOK}`'u environment variable'dan okur. Yaygın pattern: + +```shell +$ export SLACK_WEBHOOK="https://hooks.slack.com/services/T.../B.../..." +$ forgelm --config configs/run.yaml +``` + +## Abone olabileceğiniz olaylar + +| Olay | Ne zaman | +|---|---| +| `run_start` | Eğitim başlar. | +| `data_audit_complete` | `forgelm audit` sonrası. | +| `training_epoch_complete` | Her epoch sonrası. (gürültülü; genelde atlanır) | +| `benchmark_complete` | Eval suite sonrası. | +| `safety_eval_complete` | Llama Guard skorlama sonrası. | +| `auto_revert` | Otomatik geri alma tetiklendiğinde. | +| `human_approval_request` | `compliance.human_approval` engellediğinde. | +| `human_approval_granted` | Onay imzalandığında. | +| `model_exported` | `forgelm export` sonrası. | +| `run_complete` | Başarılı çıkış. | +| `run_failed` | Sıfır olmayan çıkış. | + +Seçici abone olun — çok-sık webhook spam olur. + +## Payload yapısı + +Generic format (`slack` ve `teams` template'leri bunu kendi formatlarına sarar): + +```json +{ + "event": "auto_revert", + "ts": "2026-04-29T14:33:04Z", + "run_id": "abc123", + "config_path": "configs/customer-support.yaml", + "trigger": "safety_regression", + "regressed_categories": ["S5"], + "details": {...}, + "artifacts_url": "https://compliance-store.example/abc123/" +} +``` + +## Slack template + +```yaml +output: + webhook: + url: "${SLACK_WEBHOOK}" + template: "slack" + events: ["run_complete", "run_failed", "auto_revert"] + channel: "#ml-training" # opsiyonel override + mention_on_failure: "@ml-oncall" +``` + +Üretir: + +```text +🔥 ForgeLM otomatik geri alma tetiklendi + +Koşu: customer-support v1.2.0 (abc123) +Tetikleyici: S5'te safety_regression +Restore: checkpoints/sft-base'den +Audit log: artifacts/audit_log.jsonl + +@ml-oncall lütfen incele. +``` + +## Microsoft Teams template + +```yaml +output: + webhook: + url: "${TEAMS_WEBHOOK}" + template: "teams" + events: ["auto_revert", "human_approval_request"] +``` + +Aynı veriyi action button'lı Teams MessageCard olarak üretir. + +## Generic template (özel entegrasyonlar) + +Kendi dashboard'unuz, incident sisteminiz veya pipeline'ınız için: + +```yaml +output: + webhook: + url: "https://internal.example/forgelm-events" + template: "generic" + events: ["run_start", "run_complete", "run_failed", "auto_revert"] + headers: + Authorization: "Bearer ${INCIDENT_API_TOKEN}" + timeout_seconds: 5 + retries: 3 +``` + +Endpoint yukarıdaki ham yapılandırılmış payload'u alır. ForgeLM JSON POST'lar, 2xx bekler, geçici hatalarda yeniden dener. + +## Birden çok hedef + +Farklı olayları farklı yerlere göndermek için: + +```yaml +output: + webhooks: + - url: "${SLACK_WEBHOOK}" + template: "slack" + events: ["run_complete", "run_failed"] + - url: "${PAGERDUTY_WEBHOOK}" + template: "generic" + events: ["auto_revert"] # sadece kritik + - url: "${INTERNAL_DASHBOARD_URL}" + template: "generic" + events: ["*"] # dashboard için her şey +``` + +## Güvenlik + +- **Sadece TLS.** ForgeLM üretim build'lerinde HTTP webhook URL'lerini reddeder. +- **Hassas veri redaksiyonu.** API key'ler, tam config'ler ve PII payload'larda varsayılan olarak redakte edilir. `webhook.redact: false` sadece her iki uçta da kontrol sahibi olduğunuzda override edin. +- **SSRF guard.** ForgeLM iç IP'lere (RFC 1918, link-local) işaret eden webhook URL'lerini engeller; `webhook.allow_private: true` ile açıkça izin vermediğiniz sürece. Yanlış konfigüre koşuların iç ağınızı sondalamasını önler. + +## Sık hatalar + +:::warn +**Webhook sessiz başarısız.** Webhook endpoint'inden 4xx yanıtı eğitimi başarısız etmemeli ama ForgeLM hatayı sessizce yutmamalı. `audit_log.jsonl`'da `webhook_failed` olaylarına bakın; endpoint'inizin neden reddettiğini araştırın. +::: + +:::warn +**`training_epoch_complete`'a abone olmak.** 50-epoch eğitimde 50 mesaj demek — Slack rate-limit'ler. Uçlar için `run_start` ve `run_complete` kullanın. +::: + +:::tip +**Webhook'ları `--webhook-test` ile test edin.** Canlıya geçmeden önce `forgelm --config X.yaml --webhook-test` çalıştırın — webhook'unuza sentetik payload fırlatır, formatlamayı doğrularsınız. Gerçek eğitim olmaz. +::: + +## Bkz. + +- [CI/CD Hatları](#/operations/cicd) — webhook'ların doğal yuvası. +- [Otomatik Geri Alma](#/evaluation/auto-revert) — en eyleme dönük webhook'u üretir. +- [İnsan Gözetimi](#/compliance/human-oversight) — webhook-tabanlı onay akışı. diff --git a/docs/usermanuals/tr/reference/cli.md b/docs/usermanuals/tr/reference/cli.md new file mode 100644 index 00000000..dcfeccaf --- /dev/null +++ b/docs/usermanuals/tr/reference/cli.md @@ -0,0 +1,219 @@ +--- +title: CLI Referansı +description: Her forgelm subcommand'ı ve bayrağı, auth kurulumu ve sık pattern'ler. +--- + +# CLI Referansı + +ForgeLM, subcommand'larla tek bir `forgelm` binary'si yayınlar. Bu sayfa kanonik referanstır; eğitsel rehberlik için bkz. [İlk Koşunuz](#/getting-started/first-run). + +## Üst seviye subcommand'lar + +| Komut | Yaptığı | +|---|---| +| `forgelm` (subcommand'sız) | Eğit (`--config` ile). | +| `forgelm doctor` | Ortam kontrolü — Python, CUDA, GPU, bağımlılıklar. | +| `forgelm quickstart` | Yerleşik şablonları listele veya örnekle. | +| `forgelm ingest` | PDF/DOCX/EPUB → JSONL dönüşümü. | +| `forgelm audit` | Eğitim öncesi veri denetimi. | +| `forgelm benchmark` | Model üzerinde lm-eval-harness koştur. | +| `forgelm safety-eval` | Llama Guard skorlama. | +| `forgelm chat` | Etkileşimli REPL. | +| `forgelm batch-chat` | Etkileşimsiz prompt → yanıt. | +| `forgelm export` | GGUF export ve quantization. | +| `forgelm deploy` | Deployment config üret (Ollama, vLLM, TGI vb.). | +| `forgelm verify-annex-iv` | Annex IV artifact'ını doğrula. | +| `forgelm verify-log` | Audit log zincirini doğrula. | +| `forgelm verify-gguf` | GGUF bütünlüğünü doğrula. | +| `forgelm cache-models` | Air-gap için HuggingFace modellerini önceden cache'le. | +| `forgelm cache-tasks` | lm-evaluation-harness görevlerini önceden cache'le. | +| `forgelm trend` | Son koşular arasında metric trendlerini göster. | +| `forgelm compare-runs` | Koşu metriklerini yan yana karşılaştır. | +| `forgelm approve` | İnsan onay isteğini imzala. | +| `forgelm approvals` | Bekleyen onayları listele. | + +Bunlardan herhangi biri için `forgelm --help`. + +## Üst seviye bayraklar (birçok subcommand'da) + +| Bayrak | Açıklama | +|---|---| +| `--config PATH` | YAML config dosya yolu. Eğitim için gerekli. | +| `--dry-run` | Config'i ve referansları doğrula; eğitim yok. | +| `--fit-check` | VRAM tahmini ve verdict; eğitim yok. | +| `--estimate-cost` | Uçuş öncesi maliyet tahmini; eğitim yok. | +| `--offline` | Tüm ağ çağrılarını kapat; her şey cache'lenmiş olmalı. | +| `--output-format {plain,json}` | Log formatı. CI için JSON. | +| `--verbose, -v` | Log detayını artır. | +| `--quiet, -q` | Log detayını azalt. | +| `--version` | Sürümü yazdır. | +| `--help, -h` | Yardım göster. | + +## Eğitim: `forgelm` + +En sık kullanılan pattern'ler: + +```shell +$ forgelm --config configs/run.yaml --dry-run # doğrula +$ forgelm --config configs/run.yaml --fit-check # VRAM kontrolü +$ forgelm --config configs/run.yaml # eğit +$ forgelm --config configs/run.yaml --resume # son checkpoint'ten devam +$ forgelm --config configs/run.yaml --merge # merge işi olarak çalıştır +$ forgelm --config configs/run.yaml --generate-data # sadece sentetik veri +``` + +Belirli bir checkpoint'ten devam: `--resume-from PATH`. + +## Audit: `forgelm audit` + +```shell +$ forgelm audit DATAFILE_OR_DIR \ + [--output ./audit/] \ + [--strict] \ + [--dedup-algo simhash|minhash] \ + [--dedup-threshold N] \ + [--skip-pii] [--skip-secrets] [--skip-quality] [--skip-leakage] \ + [--remove-duplicates] [--remove-cross-split-overlap=val|test] \ + [--output-clean PATH] \ + [--show-leakage] \ + [--sample-rate FLOAT] +``` + +Tam semantic için bkz. [Veri Seti Denetimi](#/data/audit). + +## Ingest: `forgelm ingest` + +```shell +$ forgelm ingest INPUT_DIR \ + --output PATH.jsonl \ + [--recursive] \ + [--strategy tokens|markdown|paragraph|sentence] \ + [--max-tokens N] [--overlap N] \ + [--pii-mask] [--secrets-mask] \ + [--pii-locale tr|de|fr|us] \ + [--language LANG] \ + [--include "*.pdf,*.md"] [--exclude "drafts/*"] \ + [--format raw|instructions|qa] +``` + +Bkz. [Doküman Ingest'i](#/data/ingestion). + +## Chat: `forgelm chat` + +```shell +$ forgelm chat CHECKPOINT \ + [--base BASE_MODEL] \ + [--temperature 0.7] [--top-p 0.9] [--max-tokens 1024] \ + [--system "system prompt"] \ + [--safety on|off] \ + [--load PATH] # kayıtlı oturum yükle +``` + +REPL içinde slash komutları: `/reset`, `/save`, `/load`, `/system`, `/temperature`, `/top_p`, `/max_tokens`, `/safety`, `/help`, `/quit`. Bkz. [Etkileşimli Chat](#/deployment/chat). + +## Export: `forgelm export` + +```shell +$ forgelm export CHECKPOINT_DIR \ + --output PATH.gguf \ + --quant q4_k_m|q5_k_m|q6_k|q8_0|q3_k_m|q2_k|fp16 \ + [--merge] # export öncesi LoRA'yı base'e merge et +``` + +Tek komutta birden çok seviye için `--quant`'ı virgülle ayırın. Bkz. [GGUF Export](#/deployment/gguf-export). + +## Deploy: `forgelm deploy` + +```shell +$ forgelm deploy CHECKPOINT_DIR \ + --target ollama|vllm|tgi|hf-endpoints|kserve|triton \ + --output PATH_OR_DIR +``` + +Bkz. [Deploy Hedefleri](#/deployment/deploy-targets). + +## Kimlik doğrulama + +ForgeLM kimlik bilgilerini environment variable'lardan okur. Asla YAML'a koymayın. + +| Sağlayıcı | Env var | Kullanılan | +|---|---|---| +| HuggingFace | `HF_TOKEN` | Geçit kontrollü modeller (Llama, Llama Guard) | +| OpenAI | `OPENAI_API_KEY` | LLM-as-judge, sentetik veri | +| Anthropic | `ANTHROPIC_API_KEY` | LLM-as-judge, sentetik veri | +| W&B | `WANDB_API_KEY` | Deney takibi | +| Cohere | `COHERE_API_KEY` | (sentetik veri) | + +YAML interpolasyonu: + +```yaml +auth: + hf_token: "${HF_TOKEN}" +synthetic: + teacher: + api_key: "${OPENAI_API_KEY}" +``` + +Env var ayarlı değilse ForgeLM net bir hatayla config yüklemede başarısız olur — eksik token nedeniyle eğitim 6 saatte çökmektense bu daha iyidir. + +## Exit kodları + +| Exit | Anlamı | +|---|---| +| 0 | Başarı | +| 1 | Config / arg hatası | +| 2 | Audit uyarıları (`--strict` ile) | +| 3 | Otomatik geri alma / regresyon | +| 4 | İnsan onayı bekliyor | +| 130 | Kullanıcı kesti (Ctrl+C) | + +Tam kontrat için bkz. [Exit Kodları](#/reference/exit-codes). + +## Environment variable'lar + +| Değişken | Ayarladığı | +|---|---| +| `HF_TOKEN` | HuggingFace auth | +| `HF_HOME` | HuggingFace cache dizini (varsayılan `~/.cache/huggingface`) | +| `HF_HUB_OFFLINE=1` | HF Hub ağ çağrılarını kapat | +| `TRANSFORMERS_OFFLINE=1` | transformers kütüphanesi ağ çağrılarını kapat | +| `HF_DATASETS_OFFLINE=1` | datasets kütüphanesi ağ çağrılarını kapat | +| `FORGELM_CACHE_DIR` | ForgeLM-özgü cache konumu | +| `FORGELM_LOG_LEVEL` | Log seviyesini override et (DEBUG, INFO, WARN, ERROR) | +| `FORGELM_RESUME_TOKEN` | API tabanlı insan onay akışı için token | + +## Sık pattern'ler + +### "Sadece eğit, beni rahatsız etme" + +```shell +$ forgelm --config configs/run.yaml --output-format json | tee run.log +``` + +### "Audit yap, temizse eğit" + +```shell +$ forgelm audit data/ --strict && forgelm --config configs/run.yaml +``` + +### "Eğit, GGUF export et, Ollama'ya deploy et" + +```yaml +# configs/run.yaml +output: + gguf: + enabled: true +deployment: + target: ollama +``` + +```shell +$ forgelm --config configs/run.yaml +# Eğitim, export ve deployment config üretimi hepsi olur. +``` + +## Bkz. + +- [Konfigürasyon Referansı](#/reference/configuration) — YAML eşi. +- [Exit Kodları](#/reference/exit-codes) — CI için kapı kontratı. +- [YAML Şablonları](#/reference/yaml-templates) — tam çalışan config'ler. diff --git a/docs/usermanuals/tr/reference/configuration.md b/docs/usermanuals/tr/reference/configuration.md new file mode 100644 index 00000000..0e191cde --- /dev/null +++ b/docs/usermanuals/tr/reference/configuration.md @@ -0,0 +1,301 @@ +--- +title: Konfigürasyon Referansı +description: ForgeLM'in anladığı her YAML alanı — tipler, varsayılanlar, notlar. +--- + +# Konfigürasyon Referansı + +Bu, ForgeLM'in kabul ettiği her YAML alanının kanonik referansıdır. Şema Pydantic ile zorlanır; `forgelm --config X.yaml --dry-run` dosyanızı şemaya karşı doğrular. + +Üst seviye config 13 bloktan oluşur: + +```yaml +model: {...} +lora: {...} +galore: {...} +datasets: [...] +training: {...} +evaluation: {...} +synthetic: {...} +merge: {...} +distributed: {...} +compliance: {...} +output: {...} +auth: {...} +deployment: {...} +``` + +## `model:` + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" # HF id veya yerel yol (gerekli) + trust_remote_code: false # sadece güveniyorsanız true + max_length: 4096 # eğitim context'i + load_in_4bit: false # QLoRA toggle + load_in_8bit: false + bnb_4bit_quant_type: "nf4" # nf4 | fp4 + bnb_4bit_compute_dtype: "bfloat16" + use_unsloth: false # desteklenen modellerde 2-5× hız + attention_implementation: "auto" # auto | flash_attention_2 | sdpa | eager + rope_scaling: + type: "linear" # linear | dynamic | yarn | longrope + factor: 4.0 + sliding_window: null + torch_dtype: "auto" +``` + +## `lora:` + +```yaml +lora: + r: 16 + alpha: 32 + dropout: 0.05 + target_modules: ["q_proj", "k_proj", "v_proj", "o_proj"] + modules_to_save: [] + use_dora: false + use_pissa: false + use_rslora: false +``` + +## `galore:` (lora alternatifi) + +```yaml +galore: + enabled: false # lora.r ile çakışır + rank: 256 + update_proj_gap: 200 + scale: 0.25 + proj_type: "std" + target_modules: ["attn", "mlp"] +``` + +## `datasets:` + +```yaml +datasets: + - path: "data/train.jsonl" # gerekli + format: "messages" # belirtilmezse otomatik algılanır + weight: 1.0 + split: "train" # train | val | test + streaming: false +``` + +Format seçenekleri: `instructions`, `messages`, `preference`, `binary`, `reward`. Bkz. [Dataset Formatları](#/concepts/data-formats). + +## `training:` + +```yaml +training: + trainer: "sft" # sft | dpo | simpo | kto | orpo | grpo + epochs: 3 + max_steps: -1 + batch_size: 4 + gradient_accumulation_steps: 1 + learning_rate: 2.0e-4 + scheduler: "cosine" + warmup_ratio: 0.03 + weight_decay: 0.0 + optimizer: "adamw_8bit" + seed: 42 + packing: false + neftune_noise_alpha: null + loss_on_completions_only: true + log_grad_norm: false + report_to: ["tensorboard"] + run_name: null + tags: [] + notes: null + + # Trainer-özgü bloklar + dpo: { beta: 0.1, loss_type: "sigmoid", reference_free: false } + simpo: { beta: 2.0, gamma: 1.0, length_normalize: true } + kto: { beta: 0.1, desirable_weight: 1.0, undesirable_weight: 1.0 } + orpo: { beta: 0.1, sft_weight: 1.0 } + grpo: + group_size: 8 + beta: 0.04 + reward_function: "my_module.score" + format_reward: 0.2 + answer_pattern: null + temperature: 0.9 +``` + +## `evaluation:` + +```yaml +evaluation: + enabled: true + max_length: null + benchmark: + enabled: false + tasks: [] + floors: {} + num_fewshot: 0 + batch_size: 8 + limit: null + safety: + enabled: false + model: "meta-llama/Llama-Guard-3-8B" + block_categories: [] + test_prompts: null + severity_threshold: "medium" + regression_tolerance: 0.05 + baseline: null + judge: + enabled: false + mode: "pairwise" + judge_model: { provider: "openai", model: "gpt-4o-mini" } + baseline_model: null + test_prompts: null + num_samples: 200 + rubric: "default" + self_consistency: 1 + swap_positions: true + budget_usd: null + trend: + enabled: false + history_file: ".forgelm/eval-history.jsonl" + lookback_runs: 10 + drift_p_threshold: 0.05 + fail_on_concern: "high" + auto_revert: + enabled: false + last_good_checkpoint: null + notify_on_revert: true + keep_failed_checkpoint: true + guards: {} +``` + +## `synthetic:` + +```yaml +synthetic: + enabled: false + teacher: { provider: "openai", model: "gpt-4o", api_key: "${OPENAI_API_KEY}" } + seed_prompts: "data/seeds.jsonl" + output: "data/synthetic.jsonl" + num_samples: 1000 + temperature: 0.7 + prompt_template: "default" + budget_usd: null + rate_limit: { requests_per_minute: 100, burst: 10 } +``` + +## `merge:` + +```yaml +merge: + enabled: false + algorithm: "ties" # linear | slerp | ties | dare | dare_ties + base_model: null + models: [{ path: "./checkpoints/v1", weight: 0.5 }] + parameters: { threshold: 0.7, density: 0.7, t: 0.5 } + output: { dir: "./checkpoints/merged", model_card: true } +``` + +## `distributed:` + +```yaml +distributed: + strategy: "single" # single | deepspeed | fsdp + zero_stage: null # 2 | 3 + cpu_offload: false + nvme_offload_path: null + fsdp_state_dict_type: "FULL_STATE_DICT" + fsdp_auto_wrap_policy: "TRANSFORMER_BASED_WRAP" + fsdp_offload_params: false + gradient_accumulation_steps: 1 +``` + +## `compliance:` + +```yaml +compliance: + annex_iv: false + data_audit_artifact: null + human_approval: false + intended_purpose: null # annex_iv: true ise gerekli + risk_classification: null + deployment_geographies: [] + responsible_party: null + version: null + standards: [] + notes: null + risk_assessment: + foreseeable_misuse: [] + mitigations: [] + residual_risks: [] + data_protection: + framework: null # GDPR | KVKK | both + lawful_basis: null + purpose: null + data_controller: null + international_transfers: { enabled: false, safeguards: null } + audit_log: + enabled: false + path: "${output.dir}/artifacts/audit_log.jsonl" + forward_to: [] + approval: + request_webhook: null + signature_method: "cli" + timeout_hours: 48 + require_role: null + quorum: 1 + post_market_plan: null + license: "Apache-2.0" +``` + +## `output:` + +```yaml +output: + dir: "./checkpoints/run" # gerekli + model_card: true + save_format: "safetensors" + save_strategy: "epoch" + save_steps: 500 + webhook: + url: null + template: "slack" + events: [] + cost_tracking: + enabled: false + rate_per_hour: {} + currency: "USD" + alert_threshold_usd: null + halt_threshold_usd: null + gguf: + enabled: false + quant_levels: ["q4_k_m"] + output_dir: "${output.dir}/gguf/" + manifest: true +``` + +## `auth:` + +```yaml +auth: + hf_token: null # ${HF_TOKEN} env tercihli + openai_api_key: null + anthropic_api_key: null +``` + +## `deployment:` + +```yaml +deployment: + target: null # ollama | vllm | tgi | hf-endpoints | kserve | triton + served_model_name: null + max_input_length: 4096 + max_total_tokens: 8192 + gpu_memory_utilization: 0.85 + chat_template: null + system_prompt_default: null +``` + +## Bkz. + +- [CLI Referansı](#/reference/cli) — YAML alanlarını tamamlayan bayraklar. +- [YAML Şablonları](#/reference/yaml-templates) — tam çalışan örnekler. diff --git a/docs/usermanuals/tr/reference/exit-codes.md b/docs/usermanuals/tr/reference/exit-codes.md new file mode 100644 index 00000000..934aaa71 --- /dev/null +++ b/docs/usermanuals/tr/reference/exit-codes.md @@ -0,0 +1,117 @@ +--- +title: Exit Kodları +description: ForgeLM'in exit-kod kontratı — CI/CD hatlarının kamuya açık API'si. +--- + +# Exit Kodları + +ForgeLM'in exit kodları kamuya açık bir kontrattır. CI/CD hatları, scheduler'lar ve dashboard'lar bunlara dayanır. Sürümler arası sessizce değişmez. + +## Kontrat + +| Exit | İsim | Anlam | Tipik CI aksiyonu | +|---|---|---|---| +| **0** | Başarı | Koşu tamamlandı; tüm kapılar geçti; checkpoint terfi etti. | Hattı sürdür | +| **1** | Config hatası | YAML geçersiz, dosya yok, env var ayarsız veya argüman bozuk. | Hızlı başarısız | +| **2** | Audit uyarıları | Audit `--strict` ile koşturuldu, uyarı seviyesi sorunlar bulundu. | Merge engelle / inceleme iste | +| **3** | Regresyon / otomatik geri alma | Benchmark veya güvenlik kapısı geçemedi; geri alındı. | İncele; terfi ETTİRME | +| **4** | İnsan onayı bekliyor | `compliance.human_approval: true` engelliyor. | Hattı tut; reviewer'ı tetikle | +| **5** | Maliyet tavanı aşıldı | `output.cost_tracking.halt_threshold_usd` aşıldı. | Maliyet aşımını incele | +| **130** | Kesildi | Kullanıcı Ctrl+C bastı. | Manuel karar | + +Diğer sıfır olmayan exit beklenmedik hata — issue açın. + +## CI pattern'lerine eşleme + +### GitHub Actions + +```yaml +- name: Train + id: train + run: forgelm --config configs/run.yaml + continue-on-error: true + +- name: Block on regression + if: steps.train.outcome == 'failure' + run: | + if [ "${{ steps.train.outputs.exit-code }}" = "3" ]; then + echo "::error::Regresyon tespit edildi — audit log'u inceleyin" + exit 1 + fi +``` + +Çoğu hat için basit pattern yeterli: + +```yaml +- name: Train + run: forgelm --config configs/run.yaml + # Sıfır olmayan exit step'i fail eder. Artifact upload step'i hâlâ çalışır (if: always()). +``` + +### GitLab CI + +```yaml +train: + script: + - forgelm --config configs/run.yaml + allow_failure: + exit_codes: [4] # exit 4 (onay bekleme) CI'yı fail etmez +``` + +## Hangi durum hangi exit + +| Durum | ForgeLM exit | +|---|---| +| YAML'da typo (ör. `learnng_rate`) | 1 | +| YAML'da `${HF_TOKEN}` ama env var yok | 1 | +| `--config` var olmayan dosyaya işaret ediyor | 1 | +| `--strict` ile audit ve PII flag'leri | 2 | +| `--strict` ile audit ve split-arası sızıntı | 3 (sızıntı uyarı değil hata) | +| DPO koşusu, Llama Guard S5 toleransı aştı | 3 | +| Benchmark hellaswag floor altına düştü | 3 | +| Final loss NaN | 3 | +| `compliance.human_approval: true` ve onay imzalanmamış | 4 | +| Maliyet eşiği eğitim ortasında aşıldı | 5 | +| Kullanıcı Ctrl+C | 130 | + +## Programatik tespit + +Otomatik parsing için ForgeLM exit kodunu bir sidecar dosyaya da yazar: + +```text +checkpoints/run/artifacts/exit_status.txt: + +3 +trigger=safety_regression +regressed_categories=S5 +restored_from=./checkpoints/sft-base +``` + +Ham exit kodlarını korumayan log aggregator'lara stream eden CI runner'larında yardımcı olur. + +## "exit 0" tam olarak ne garanti eder + +0 ile çıkan koşu: +- Config'i hatasız doğrulamış. +- Modeli ve dataset'i yüklemiş. +- Tüm konfigüre eğitim adımlarını tamamlamış. +- Her benchmark floor'unu geçmiş. +- Her güvenlik eşiğini geçmiş. +- Model card yazmış. +- Annex IV paketi yazmış (konfigüre ise). +- Manifest.json'u tüm artifact'lar üzerinde SHA-256 ile yazmış. +- Opsiyonel: GGUF, deployment config yazmış. +- Audit log'u `run_complete` ile kapatmış. + +Bunlardan biri başarısız olursa exit kod sıfır değildir. Tasarım gereği "kısmi başarı" exit kodu yok. + +## Uyumluluk garantisi + +Exit kodları 0-5 sürümler arası kararlıdır. Yeni kodlar eklenebilir (6, 7, …) ama mevcutların semantiği değişmez. Yukarıdaki kontrata pinli CI hatları ForgeLM yükseltmelerinde çalışmaya devam eder. + +## Bkz. + +- [CI/CD Hatları](#/operations/cicd) — bu kontratı kullanan pattern'ler. +- [CLI Referansı](#/reference/cli) — bu kodları üreten tüm komutlar. +- [Otomatik Geri Alma](#/evaluation/auto-revert) — exit 3 üretir. +- [İnsan Gözetimi](#/compliance/human-oversight) — exit 4 üretir. diff --git a/docs/usermanuals/tr/reference/yaml-templates.md b/docs/usermanuals/tr/reference/yaml-templates.md new file mode 100644 index 00000000..11c5663b --- /dev/null +++ b/docs/usermanuals/tr/reference/yaml-templates.md @@ -0,0 +1,356 @@ +--- +title: YAML Şablonları +description: Yaygın iş akışları için tam çalışan konfigürasyonlar — kopyala, uyarla, koştur. +--- + +# YAML Şablonları + +Bu şablonlar CI'da test ediliyor. Birini kopyalayın, isim ve yolları değiştirin, koşturun. + +## Müşteri-destek asistanı (SFT → DPO) + +Multi-turn yardımsever + güvenli model — en yaygın üretim pattern'i. + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true + max_length: 4096 + +lora: + r: 16 + alpha: 32 + use_dora: true + +datasets: + - path: "data/customer-support-sft.jsonl" + format: "messages" + - path: "data/customer-support-prefs.jsonl" + format: "preference" + split: "train" + +training: + trainer: "dpo" + epochs: 1 + batch_size: 2 + gradient_accumulation_steps: 8 + learning_rate: 5.0e-6 + scheduler: "cosine" + warmup_ratio: 0.05 + packing: true + dpo: + beta: 0.1 + loss_type: "sigmoid" + report_to: ["tensorboard"] + +evaluation: + benchmark: + enabled: true + tasks: ["hellaswag", "arc_easy", "truthfulqa"] + floors: + hellaswag: 0.55 + arc_easy: 0.70 + truthfulqa: 0.45 + safety: + enabled: true + model: "meta-llama/Llama-Guard-3-8B" + block_categories: ["S1", "S2", "S5", "S10"] + severity_threshold: "medium" + auto_revert: + enabled: true + +compliance: + annex_iv: true + data_audit_artifact: "./audit/data_audit_report.json" + human_approval: true + intended_purpose: "Türk telekomu için müşteri-destek asistanı" + risk_classification: "high-risk" + deployment_geographies: ["TR", "EU"] + responsible_party: "Acme Corp " + version: "1.2.0" + +output: + dir: "./checkpoints/customer-support-v1.2" + model_card: true + webhook: + url: "${SLACK_WEBHOOK}" + template: "slack" + events: ["run_complete", "run_failed", "auto_revert"] + gguf: + enabled: true + quant_levels: ["q4_k_m"] + +deployment: + target: "ollama" +``` + +## PDF'lerden alan uzmanı (sadece SFT) + +"İç dokümanlarımız üzerinde fine-tune et" senaryosu için. + +```yaml +# Önce çalıştırın: +# forgelm ingest ./regulatory-docs/ --recursive --strategy markdown \ +# --pii-mask --secrets-mask --output data/regulatory.jsonl +# forgelm audit data/regulatory.jsonl + +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true + max_length: 8192 + +lora: + r: 32 + alpha: 64 + +datasets: + - path: "data/regulatory.jsonl" + format: "instructions" + +training: + trainer: "sft" + epochs: 3 + batch_size: 2 + gradient_accumulation_steps: 16 + learning_rate: 2.0e-4 + scheduler: "cosine" + warmup_ratio: 0.03 + packing: true + neftune_noise_alpha: 5.0 + +evaluation: + benchmark: + enabled: true + tasks: ["mmlu"] + floors: { mmlu: 0.48 } + safety: + enabled: true + block_categories: ["S5", "S6"] # iftira + uzmanlık tavsiyesi + +compliance: + annex_iv: true + intended_purpose: "Compliance ekibi için regülasyon Q&A asistanı" + risk_classification: "high-risk" + deployment_geographies: ["EU", "TR"] + responsible_party: "Acme Compliance Team" + +output: + dir: "./checkpoints/regulatory-qa" +``` + +## GRPO matematik akıl yürütme + +```yaml +model: + name_or_path: "./checkpoints/sft-base" # önce SFT, sonra GRPO + max_length: 4096 + +lora: + r: 16 + alpha: 32 + +datasets: + - path: "data/math-problems.jsonl" + format: "reward" + +training: + trainer: "grpo" + epochs: 1 + batch_size: 1 + gradient_accumulation_steps: 4 + learning_rate: 1.0e-6 + scheduler: "constant" + grpo: + group_size: 8 + beta: 0.04 + reward_function: "rewards.math_score" + format_reward: 0.2 + answer_pattern: "\\boxed\\{(.*?)\\}" + temperature: 0.9 + +evaluation: + benchmark: + enabled: true + tasks: ["gsm8k"] + floors: { gsm8k: 0.55 } + +output: + dir: "./checkpoints/math-grpo" +``` + +```python +# rewards.py +def math_score(prompt: str, response: str, ground_truth: str) -> float: + import re + m = re.search(r'\\boxed\{(.*?)\}', response) + if not m: + return -0.5 + try: + return 1.0 if float(m.group(1)) == float(ground_truth) else -1.0 + except ValueError: + return -0.5 +``` + +## ZeRO-3 ile çoklu-GPU 70B + +8× A100 80GB üzerinde 70B model eğitmek için. + +```yaml +model: + name_or_path: "meta-llama/Llama-3.1-70B-Instruct" + max_length: 4096 + attention_implementation: "flash_attention_2" + +lora: + r: 32 + alpha: 64 + +datasets: + - path: "data/train.jsonl" + format: "messages" + +training: + trainer: "sft" + epochs: 2 + batch_size: 1 + gradient_accumulation_steps: 16 + learning_rate: 1.0e-4 + scheduler: "cosine" + +distributed: + strategy: "deepspeed" + zero_stage: 3 + cpu_offload: false # 8 A100 yeterli + +evaluation: + benchmark: + enabled: true + tasks: ["mmlu"] + floors: { mmlu: 0.65 } + +output: + dir: "./checkpoints/llama-70b-finetune" +``` + +Başlatma: `accelerate launch --num_processes 8 -m forgelm --config configs/llama-70b.yaml` + +## Sentetik veri + SFT + +GPT-4o'yu 7B student'a damıt. + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true + max_length: 4096 + +datasets: + - path: "data/seed-prompts.jsonl" + format: "instructions" + - path: "data/synthetic.jsonl" # --generate-data ile üretildi + format: "instructions" + +training: + trainer: "sft" + epochs: 2 + learning_rate: 2.0e-4 + +synthetic: + enabled: true + teacher: + provider: "openai" + model: "gpt-4o" + api_key: "${OPENAI_API_KEY}" + seed_prompts: "data/seed-prompts.jsonl" + output: "data/synthetic.jsonl" + num_samples: 5000 + temperature: 0.7 + budget_usd: 50.0 + +output: + dir: "./checkpoints/distilled" +``` + +Çalıştır: + +```shell +$ forgelm --config configs/distill.yaml --generate-data # data/synthetic.jsonl üretir +$ forgelm --config configs/distill.yaml # seed + sentetik üzerinde eğitir +``` + +## Model birleştirme + +Üç uzman LoRA'yı tek generalist'e birleştir. + +```yaml +merge: + enabled: true + algorithm: "ties" + base_model: "Qwen/Qwen2.5-7B-Instruct" + models: + - { path: "./checkpoints/customer-support", weight: 0.4 } + - { path: "./checkpoints/code-assistant", weight: 0.3 } + - { path: "./checkpoints/math-reasoning", weight: 0.3 } + parameters: + threshold: 0.7 + output: + dir: "./checkpoints/merged" + model_card: true + evaluation: + benchmark: + tasks: ["mmlu", "humaneval", "gsm8k"] + floors: { mmlu: 0.50, humaneval: 0.40, gsm8k: 0.50 } +``` + +```shell +$ forgelm --merge --config configs/merge.yaml +``` + +## Air-gap'e hazır müşteri destek + +Müşteri-destek şablonuyla aynı, ama her şey önceden cache'lenmiş ve `--offline` zorlanmış. + +```yaml +# configs/customer-support-airgap.yaml +# Ön gereksinim: forgelm cache-models / cache-tasks zaten koşturuldu + +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" # cache'lenmiş olmalı + load_in_4bit: true + +# ... (müşteri-destek şablonuyla aynı eğitim config'i) + +evaluation: + safety: + enabled: true + model: "meta-llama/Llama-Guard-3-8B" # cache'lenmiş olmalı + judge: + enabled: false # OpenAI judge offline'da yok + trend: + enabled: true # yerel + +compliance: + audit_log: + forward_to: + - type: "syslog" + host: "audit.internal:514" # sadece-iç + protocol: "tcp" + +output: + webhook: + url: "https://internal-webhooks.example/forgelm" + allow_private: true # iç IP'ler için gerekli +``` + +Çalıştır: + +```shell +$ HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \ + forgelm --config configs/customer-support-airgap.yaml --offline +``` + +## Bkz. + +- [Konfigürasyon Referansı](#/reference/configuration) — bu şablonların kullandığı her alan. +- [CLI Referansı](#/reference/cli) — bu şablonların beklediği komutlar. +- [İlk Koşunuz](#/getting-started/first-run) — müşteri-destek şablonu adım adım. diff --git a/docs/usermanuals/tr/training/distributed.md b/docs/usermanuals/tr/training/distributed.md new file mode 100644 index 00000000..ccb9e126 --- /dev/null +++ b/docs/usermanuals/tr/training/distributed.md @@ -0,0 +1,148 @@ +--- +title: Dağıtık Eğitim +description: DeepSpeed ZeRO, FSDP ve Unsloth backend'i ile çoklu-GPU eğitim. +--- + +# Dağıtık Eğitim + +Modeliniz tek GPU belleğinden büyüdüğünde — ya da sadece daha hızlı eğitmek istediğinizde — dağıtık eğitim devreye girer. ForgeLM DeepSpeed ZeRO-2/3, PyTorch FSDP ve Unsloth tek-GPU hızlandırma backend'ini destekler. + +## Karar ağacı + +```mermaid +flowchart TD + Q1{Kaç GPU
var?} + Q2{Tek GPU
OOM mu?} + Q3{Çoklu-node
gerekli mi?} + Q4{DeepSpeed mi
PyTorch yerli mi?} + + Q1 -->|1| Q2 + Q1 -->|2-8| Q4 + Q1 -->|>8 node| Q3 + Q2 -->|Hayır| Unsloth([Unsloth + LoRA]) + Q2 -->|Evet| QLoRA([QLoRA]) + Q3 --> ZeRO3([ZeRO-3]) + Q4 -->|DeepSpeed| Z[ZeRO-2 veya ZeRO-3] + Q4 -->|PyTorch yerli| FSDP([FSDP]) + + classDef question fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + classDef result fill:#1c2030,stroke:#22c55e,color:#e6e7ec + class Q1,Q2,Q3,Q4 question + class Unsloth,QLoRA,ZeRO3,Z,FSDP result +``` + +## Backend özeti + +| Backend | Çoklu-GPU? | Çoklu-node? | Notlar | +|---|---|---|---| +| **Tek GPU + Unsloth** | Hayır | Hayır | Llama/Qwen/Mistral'da vanilla'dan 2-5× hızlı. Tek GPU'daysanız önce bunu deneyin. | +| **DeepSpeed ZeRO-2** | Evet | Evet | Optimizer state'i sharder. İyi hız, her modelde çalışır. | +| **DeepSpeed ZeRO-3** | Evet | Evet | Optimizer + gradient + parametre sharder. Çok büyük modeller için şart. | +| **DeepSpeed ZeRO-3 Offload** | Evet | Evet | CPU/NVMe'ye boşaltır. Devasa modelleri sığdırmak için hızdan ödün verir. | +| **FSDP** | Evet | Evet | PyTorch yerli. Aynı konfigürasyonda ZeRO-3'ten biraz hızlı; ekosistemi daha az olgun. | + +## Unsloth (tek GPU) + +Unsloth, Llama, Qwen, Mistral ve birkaç model için drop-in optimizasyondur. Attention ve MLP katmanlarını Triton'da yeniden yazarak ~2-5× hızlanma sağlar; kalite kaybı yoktur. + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + use_unsloth: true # ihtiyacınız olan tek bayrak + +training: + trainer: "sft" + # ... eğitim config'i değişmez +``` + +:::tip +Unsloth model-özgü kernel'lere sahiptir. Mimariniz desteklenmiyorsa ForgeLM uyarı bırakır ve standart backend'e döner. Desteklenen aileler [Konfigürasyon Referansı](#/reference/configuration)'nda listelenmiştir. +::: + +## DeepSpeed ZeRO-2 + +ZeRO-2 optimizer state'i sharder (Adam gibi adaptif optimizer'larda en ağır VRAM bileşeni). 4-8 GPU'da 13B-30B modeller için etkili. + +```yaml +distributed: + strategy: "deepspeed" + zero_stage: 2 + gradient_accumulation_steps: 4 + cpu_offload: false +``` + +Başlatma: + +```shell +$ accelerate launch --num_processes 4 -m forgelm --config configs/run.yaml +# veya +$ deepspeed --num_gpus 4 -m forgelm --config configs/run.yaml +``` + +## DeepSpeed ZeRO-3 + +ZeRO-3 ek olarak gradient ve parametreleri de GPU'lar arası sharder. Her GPU modelin sadece `1/N`'ini tutar. 70B+ modeller için şart. + +```yaml +distributed: + strategy: "deepspeed" + zero_stage: 3 + gradient_accumulation_steps: 8 + cpu_offload: false # 70B'i 8x24 GB'a sığdırmak için true + nvme_offload_path: null # ZeRO-Infinity için NVMe yolu +``` + +| Model | GPU | ZeRO-3 + offload? | +|---|---|---| +| 30B | 4× A100 40 GB | Opsiyonel | +| 70B | 8× A100 40 GB | CPU offload gerekli | +| 70B | 4× A100 80 GB | Offload gerekmez | +| 405B | 8× H100 80 GB | NVMe offload | + +## FSDP (PyTorch yerli) + +FSDP, ZeRO-3 gibi sharder ama PyTorch'un yerli FullyShardedDataParallel'ini kullanır. Aynı kurulumda biraz hızlı; ekosistem desteği biraz daha az (ör. bazı HF entegrasyonları DeepSpeed bekler). + +```yaml +distributed: + strategy: "fsdp" + fsdp_state_dict_type: "FULL_STATE_DICT" + fsdp_auto_wrap_policy: "TRANSFORMER_BASED_WRAP" + fsdp_offload_params: false +``` + +## Gradient accumulation + +Hangi backend'i kullanırsanız kullanın, gradient accumulation VRAM'in izin verdiğinden büyük etkili batch size'a izin verir: + +```yaml +training: + batch_size: 1 # cihaz başına + gradient_accumulation_steps: 32 # etkili batch = 1 × 32 × num_gpus +``` + +8 GPU × 1 batch × 32 accumulation = 256 etkili batch size — büyük eğitim koşularının çoğunun hedefi. + +## Sık hatalar + +:::warn +**ZeRO-3 + LoRA yüklemesi başarısız.** ZeRO-3, eğitilmeyen parametreler için özel işleme gerektirir. `lora.modules_to_save`'i dikkatli ayarlayın ve raw `python -m` yerine `accelerate launch` kullanın. +::: + +:::warn +**DeepSpeed ve FSDP config'lerini karıştırmak.** Birini seçin. Şema, aynı anda `distributed.zero_stage` ve `distributed.fsdp_*` ayarlamayı reddeder. +::: + +:::warn +**Node'lar arası tutarsız batch boyutları.** Tüm node'lar batch size ve accumulation üzerinde anlaşmalı. ForgeLM uyumsuzlukta erkenden hata verir; her node'dan doğrulamayı unutmayın — başlatma node'undan `--dry-run` yeterli. +::: + +:::tip +Çoklu-node için node'lar arası SSH erişimi yapılandırın ve node listesini kaydetmek için `accelerate config` kullanın. ForgeLM ortaya çıkan config'i otomatik alır. +::: + +## Bkz. + +- [GaLore](#/training/galore) — daha az VRAM'le full-parametre eğitim, ZeRO-3 alternatifi. +- [VRAM Fit-Check](#/operations/vram-fit-check) — çoklu-GPU iş başlatmadan önce doğrula. +- [CI/CD Hatları](#/operations/cicd) — otomatik hatlarda çoklu-GPU eğitim. diff --git a/docs/usermanuals/tr/training/dpo.md b/docs/usermanuals/tr/training/dpo.md new file mode 100644 index 00000000..c041b80e --- /dev/null +++ b/docs/usermanuals/tr/training/dpo.md @@ -0,0 +1,202 @@ +--- +title: Direct Preference Optimization (DPO) +description: Modeli RL veya reward model olmadan chosen/rejected çiftleriyle hizalayın. +--- + +# Direct Preference Optimization (DPO) + +DPO, modeli doğrudan (chosen, rejected) yanıt çiftleriyle eğitir; reinforcement learning'in karmaşıklığı veya ayrı bir reward model eğitmek gerekmeden çıktıları insan tercihleriyle hizalar. SFT'den sonra en yaygın alignment tekniğidir. + +## Ne zaman DPO + +```mermaid +flowchart TD + Q1{Tercih
çiftleri var mı?} + Q2{Referans model
bellekte mi?} + Q3{VRAM
dar mı?} + Q4{Sadece ikili
geri bildirim mi?} + SFT[SFT kullan] + DPO([DPO kullan]) + SIMPO[SimPO kullan] + KTO[KTO kullan] + QLORA[QLoRA + DPO] + + Q1 -->|Hayır, sadece pozitif| SFT + Q1 -->|Evet| Q4 + Q4 -->|Evet, tek yanıt| KTO + Q4 -->|Hayır, eşli| Q2 + Q2 -->|Hayır| SIMPO + Q2 -->|Evet| Q3 + Q3 -->|Evet| QLORA + Q3 -->|Hayır| DPO + + classDef question fill:#1c2030,stroke:#f97316,color:#e6e7ec + classDef recommend fill:#161a24,stroke:#22c55e,color:#e6e7ec + classDef alternative fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + class Q1,Q2,Q3,Q4 question + class DPO,QLORA recommend + class SFT,SIMPO,KTO alternative +``` + +| DPO kullan: | Kullanma: | +|---|---| +| Tercih çiftleri (ör. agent thumbs-up/down) var. | Sadece pozitif örnek var. [SFT](#/training/sft). | +| SFT yaptınız, çıktıları hizalamak istiyorsunuz. | Bellekte referans model yok. [SimPO](#/training/simpo). | +| Kararlı, çalışılmış algoritma. | VRAM dar — DPO ~2× SFT belleği. | +| Closed-form gradient (sampling yok). | Sadece tek-yanıt ikili geri bildirim. [KTO](#/training/kto). | + +:::tip +Çoğu üretim ekibi sıralı **SFT → DPO** kullanır: SFT format ve içerik, DPO yanıtlar arası tercihleri keskinleştirir. ORPO ikisini birleştirir ama biraz daha az esnek. +::: + +## Hızlı örnek + +```yaml +model: + name_or_path: "./checkpoints/sft-base" + max_length: 4096 + +lora: + r: 16 + alpha: 32 + +datasets: + - path: "data/preferences.jsonl" + format: "preference" + +training: + trainer: "dpo" + epochs: 1 + batch_size: 2 + learning_rate: 5.0e-6 # SFT'in ~10× küçük + dpo: + beta: 0.1 + +output: + dir: "./checkpoints/dpo" +``` + +## Veri formatı + +Preference formatı: her satırda `prompt`, `chosen` yanıt, `rejected` yanıt. + +```json +{"prompt": "Aboneliği nasıl iptal ederim?", "chosen": "Ayarlar → Faturalandırma…", "rejected": "Sadece ödemeyi durdur."} +``` + +ForgeLM audit `chosen == rejected` satırları flagler — preference toplamada sık bug. + +## Konfigürasyon parametreleri + +| Parametre | Tip | Vars. | Açıklama | +|---|---|---|---| +| `beta` | float | `0.1` | KL düzenlemesi. Düşük = referansa yakın, yüksek = agresif tercih kayması. | +| `loss_type` | string | `"sigmoid"` | `sigmoid` (orijinal), `hinge`, `ipo`, `kto`. | +| `label_smoothing` | float | `0.0` | Gürültülü annotasyonlarda yumuşatma. | +| `reference_free` | bool | `false` | Referans modeli atla (SimPO'ya yakın). | +| `reference_model` | string | (auto) | Açık referans modeli yolu. | +| `loss_dpop_lambda` | float | `null` | DPO-Positive (DPOP) regülarizasyonu. `0.5` iyi başlangıç. | + +## Bellek ve compute + +DPO bellek-aç. Hem policy hem referans modeli VRAM'de aynı anda tutar. + +:::warn +**Eşdeğer SFT'in ~2× VRAM'i.** 12 GB SFT'e sığan 7B model, aynı `max_length` ile DPO için 22-24 GB ister. Çözümler: +- **QLoRA + DPO** — her ikisi 4-bit. Bkz. [LoRA](#/training/lora). +- `max_length` 4096 → 2048. +- **SimPO**'ya geç. Bkz. [SimPO](#/training/simpo). +- `reference_free: true`. +::: + +Her zaman uzun DPO öncesi `--fit-check` çalıştırın. + +## `beta` seçimi + +`beta` en önemli DPO hyperparam'ıdır. + +| `beta` | Davranış | Kullan | +|---|---|---| +| `0.01 – 0.05` | Çok yumuşak; referansa yakın. | Yüksek-kalite, dar tercih sinyali; büyük dataset. | +| `0.1` | Varsayılan. Dengeli. | Çoğu iş akışı. **Buradan başla.** | +| `0.3 – 0.5` | Agresif kayma. | Kaba tercihler, küçük dataset. | +| `> 0.5` | Genelde kararsız. | Nadir. | + +:::tip +Eğitim loss'u düşüyor ama eval metrikleri geriliyorsa tercihlere over-fit oluyorsunuz — `beta`'yı *düşür*. Tercihler hiç kaymıyorsa `beta`'yı *yükselt* veya `chosen == rejected` kontrol et. +::: + +## Güvenlik değerlendirmesiyle DPO + +```mermaid +sequenceDiagram + participant User as Sen + participant FL as ForgeLM + participant Eval as Eval pipeline + participant Guard as Llama Guard + participant Bench as lm-eval-harness + participant Audit as Audit log + + User->>FL: forgelm --config dpo.yaml + FL->>FL: SFT checkpoint referans olarak yüklendi + FL->>FL: DPO eğitimi (epoch 1..N) + FL->>Eval: Post-train değerlendirme + Eval->>Guard: S1-S14 üzerinde skor + Guard-->>Eval: Kategori başına güven + Eval->>Bench: Benchmark suite + Bench-->>Eval: Görev başına doğruluk + alt Eşik aşıldı + Eval->>FL: Regresyon + FL->>FL: SFT checkpoint'e geri al + FL->>Audit: Olay kaydı ekle + FL-->>User: Exit 3 + yapılandırılmış rapor + else Eşikler geçti + FL->>Audit: Başarı kaydı + FL-->>User: Exit 0 + DPO checkpoint + end +``` + +```yaml +training: + trainer: "dpo" + dpo: { beta: 0.1 } + +evaluation: + safety: + enabled: true + model: "meta-llama/Llama-Guard-3-8B" + block_categories: ["S1", "S2", "S5", "S10"] + benchmark: + tasks: ["truthfulqa", "hellaswag"] + floors: { truthfulqa: 0.45 } + +compliance: + human_approval: true # Article 14 kapısı +``` + +Post-train Llama Guard puanları bloklu kategorilerde regresyon gösterirse ForgeLM otomatik olarak DPO öncesi checkpoint'e döner. + +## Sık hatalar + +:::warn +**Aynı `chosen` ve `rejected`.** Belirti: DPO loss anında ~0'a yakınsar. Çözüm: `forgelm audit` koşturun. +::: + +:::warn +**Çok yüksek learning rate.** DPO learning rate'e duyarlı. Full fine-tune için 5e-6, LoRA-on-DPO için 1e-5'ten başlayın. SFT learning rate'leri (1e-4 - 5e-4) sapmaya yol açar. +::: + +:::warn +**Referans model drift.** SFT ve DPO'yu farklı LoRA adapter'larıyla eğitirseniz DPO'nun referans modeli istediğiniz olmayabilir. SFT checkpoint'ini açık olarak `model.name_or_path`'a verin. +::: + +:::danger +**Tek dataset'te SFT ve DPO karıştırmak.** SFT-format satırlarını (`{prompt, completion}`) DPO-format satırlarıyla (`{prompt, chosen, rejected}`) aynı JSONL'a koymayın. Veri loader yönlendiremez. Ayrı dosyalar kullanın. +::: + +## Bkz. + +- [SFT](#/training/sft) — DPO'nun olağan ön gereksinimi. +- [SimPO](#/training/simpo) — referans modelsiz, daha az VRAM. +- [ORPO](#/training/orpo) — SFT ve DPO'yu birleştirir. +- [Otomatik Geri Alma](#/evaluation/auto-revert) — tercih eğitiminin güvenlik ağı. diff --git a/docs/usermanuals/tr/training/galore.md b/docs/usermanuals/tr/training/galore.md new file mode 100644 index 00000000..5b6b4d3b --- /dev/null +++ b/docs/usermanuals/tr/training/galore.md @@ -0,0 +1,92 @@ +--- +title: GaLore +description: LoRA seviyesinde bellek maliyetiyle full-parametre eğitim — gradient'i düşük-rank uzaya projekte ederek. +--- + +# GaLore + +GaLore (**G**radient **L**ow-**R**ank Projection) bir modelin *tüm* parametrelerini eğitir — ama LoRA seviyesindeki bellek maliyetiyle. Optimizer state'in tamamını saklamak yerine GaLore gradient'leri düşük-rank bir alt uzaya projekte eder ve eğitim ilerledikçe bu projeksiyonu periyodik olarak yeniler. + +Sonuç: full fine-tune kalitesi, LoRA'ya yakın bellek. + +## Ne zaman GaLore + +| GaLore tercih edin | LoRA / QLoRA tercih edin | +|---|---| +| Full-parametre eğitim istiyorsunuz ama VRAM dar. | Küçük bir adapter ihtiyacınızı karşılıyor. | +| LoRA yetersiz kalıyor — yakınsamadan önce kalite plato yapıyor. | Rank 32-64 LoRA çıtanızı geçiyor. | +| Adım başına ~%15-20 daha yavaş eğitime razısınız. | Wall-clock hızı ham kaliteden önemli. | +| Her ağırlığın önemli olduğu matematik veya akıl yürütme modeli. | Talimat ayarı yapıyorsunuz. | + +## Hızlı örnek + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: false # GaLore full precision'ı tercih eder + max_length: 4096 + +galore: + enabled: true + rank: 256 # LoRA'dan yüksek — projeksiyon rank'i + update_proj_gap: 200 # her N adımda bir yeniden projekte et + scale: 0.25 + proj_type: "std" # std (varsayılan), reverse_std, right, left + +training: + trainer: "sft" + learning_rate: 1.0e-5 # full-FT learning rate, LoRA'nınki değil + optimizer: "galore_adamw_8bit" + +output: + dir: "./checkpoints/galore" +``` + +`galore.enabled: true` iken ForgeLM otomatik olarak GaLore-uyumlu optimizer'ı kullanır; aynı koşuda `lora` blok'unu konfigüre etmeyin. + +## Parametreler + +| Parametre | Tip | Vars. | Açıklama | +|---|---|---|---| +| `enabled` | bool | `false` | Ana anahtar. | +| `rank` | int | `256` | Gradient projeksiyon rank'i. Yüksek = full-FT'ye yakın, daha çok bellek. | +| `update_proj_gap` | int | `200` | Yeniden projeksiyon adım aralığı. Düşük = değişen gradient'lere hızlı uyum. | +| `scale` | float | `0.25` | Projekte edilmiş gradient'lerin ölçeği. | +| `proj_type` | string | `"std"` | Projeksiyon yönü. Yakınsama tıkanırsa deneyin. | +| `target_modules` | list | `["attn", "mlp"]` | Hangi modüllerin gradient'leri projekte edilecek. | + +## Bellek karşılaştırması + +7B model, `max_length: 4096`, batch size 1 için: + +| Yöntem | Eğitilebilir param | VRAM (full precision) | VRAM (4-bit base) | +|---|---|---|---| +| Full FT | %100 | 56 GB | yok | +| LoRA r=16 | %0.2 | 18 GB | 9 GB (QLoRA) | +| **GaLore r=256** | **%100** | **22 GB** | yok | + +Yani GaLore r=256 ile 7B modeli tek 24 GB GPU'da full fine-tune edebilirsiniz — kabaca full-precision LoRA ile aynı VRAM, ama her ağırlığa erişimle. + +## Compute + +GaLore adım başına LoRA'dan ~%15-20 daha yavaştır; projeksiyon ve yeniden projeksiyon overhead'i yüzünden. Uçtan uca fark genelde kapanır: GaLore tüm parametre uzayına erişimi olduğundan sıklıkla daha az adımda yakınsar. + +## Sık hatalar + +:::warn +**GaLore'u LoRA ile birleştirmeye çalışmak.** Bunlar alternatiftir, tamamlayıcı değil. ForgeLM şeması aynı anda `lora.r` ve `galore.enabled` ayarlamayı reddeder. +::: + +:::warn +**LoRA learning rate'i kullanmak.** GaLore full-parametre — full-FT learning rate'leri kullanın (1e-5 - 5e-5), LoRA'nınkiler değil (1e-4 - 5e-4). Yanlış LR'da eğitim sapar. +::: + +:::warn +**`update_proj_gap`'i çok yüksek ayarlamak.** Seyrek yeniden projeksiyon, gradient alt uzayının optimizasyon yörüngesini takip edememesi anlamına gelir. Varsayılan 200 makul; 500'ün üzerine çıkmayın. +::: + +## Bkz. + +- [LoRA, QLoRA, DoRA](#/training/lora) — daha sık tercih edilen alternatif. +- [Dağıtık Eğitim](#/training/distributed) — tek GPU'dan büyük modeller için. +- [Konfigürasyon Referansı](#/reference/configuration) — tüm GaLore parametre listesi. diff --git a/docs/usermanuals/tr/training/grpo.md b/docs/usermanuals/tr/training/grpo.md new file mode 100644 index 00000000..2cb850d6 --- /dev/null +++ b/docs/usermanuals/tr/training/grpo.md @@ -0,0 +1,131 @@ +--- +title: Group Relative Policy Optimization (GRPO) +description: Akıl yürütme için reinforcement learning — yerleşik shaping ile reward fonksiyonuna karşı eğit. +--- + +# Group Relative Policy Optimization (GRPO) + +GRPO, ForgeLM'in reinforcement-learning trainer'ıdır. Model her prompt için birkaç yanıt üretir, reward fonksiyonunuz onları skorlar, GRPO yüksek-reward çıktıları desteklemek için policy'i günceller. Doğrulanabilir doğruluğu olan görevler (matematik, kod) veya programatik kalite sinyalleri için doğru seçim. + +## Ne zaman GRPO + +| GRPO kullan: | DPO/SimPO kullan: | +|---|---| +| Reward fonksiyonu yazabiliyorsunuz (math grader, test runner). | Kalite sinyali sadece insan tercihleri. | +| Görevlerin doğrulanabilir doğru cevabı var. | Açık uçlu görevler ("pazarlama maili yaz"). | +| Doğruluk dışında format-shaping reward istiyorsunuz. | Kararlı, çalışılmış eğitim dinamiği. | +| Reasoning model kuruyorsunuz. | Chat asistanı kuruyorsunuz. | + +```mermaid +flowchart LR + A[Prompt] --> B[N yanıt örnekle] + B --> C[Her birini reward
fn ile skorla] + C --> D[Group-relative
advantage hesapla] + D --> E[Policy güncelle] + E --> A + classDef step fill:#1c2030,stroke:#f97316,color:#e6e7ec + classDef io fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + class A,E io + class B,C,D step +``` + +## Hızlı örnek + +```yaml +model: + name_or_path: "./checkpoints/sft-base" + max_length: 4096 + +datasets: + - path: "data/math-prompts.jsonl" + format: "reward" + +training: + trainer: "grpo" + epochs: 1 + batch_size: 1 + learning_rate: 1.0e-6 + grpo: + group_size: 8 + beta: 0.04 + reward_function: "my_reward.score" + format_reward: 0.2 +``` + +```python +# my_reward.py +def score(prompt: str, response: str, ground_truth: str) -> float: + answer = parse_number(response) + if answer is None: + return -0.5 + return 1.0 if abs(answer - float(ground_truth)) < 1e-6 else -1.0 +``` + +## Yerleşik format shaping + +ForgeLM şunları ödüllendiren varsayılan reward shaper ile gelir: +- **Format uyumu** — çıktı beklenen formatla biten net cevapla bitiyor (ör. matematik için `\boxed{...}`). +- **Uzunluk uyumu** — ne çok kısa ne dağılarak uzun. +- **Akıl yürütme yapısı** — son cevaptan önce chain-of-thought. + +```yaml +training: + grpo: + reward_function: "my_reward.score" # %80 ağırlık + format_reward: 0.2 # %20 shaper + answer_pattern: '\\boxed\\{(.*?)\\}' # "son cevap" regex'i +``` + +## Parametreler + +| Parametre | Tip | Vars. | Açıklama | +|---|---|---|---| +| `group_size` | int | `8` | Prompt başına örneklenen yanıt. Yüksek = kararlı advantage, çok compute. | +| `beta` | float | `0.04` | KL düzenlemesi. GRPO'nunki DPO'dan çok küçük çünkü gradient sinyali güçlü. | +| `reward_function` | string | `null` | Reward fonksiyonunuza dotted path. | +| `format_reward` | float | `0.0` | Yerleşik format shaper ağırlığı. `0.2` mantıklı. | +| `answer_pattern` | string | `null` | "Son cevap"ı çıkarmak için regex. | +| `temperature` | float | `0.9` | Sampling sıcaklığı. Yüksek = çeşitli yanıtlar. | +| `max_completion_length` | int | `2048` | Üretilen yanıt uzunluğu sınırı. | + +## Bellek + +GRPO en ağır trainer: +- Prompt başına `group_size` yanıt üretir (varsayılan 8) — DPO'nun 8× inference maliyeti. +- Bellekte referans model tutar. +- Reward computation ek model yükleyebilir. + +| Model | LoRA | `group_size` | VRAM (QLoRA) | +|---|---|---|---| +| 7B | evet | 8 | 18 GB | +| 13B | evet | 8 | 28 GB (40 GB gerekir) | +| 7B | hayır | 8 | ZeRO-3 gerekir | + +## Sık hatalar + +:::warn +**Yanlış ölçekte reward.** `[0, 1]` (veya `[-1, 1]`) en iyi çalışır. Sınırsız reward (ör. `correct ? 1000 : 0`) gradient patlamasına yol açar. Mantıklı sınırlı aralığa normalize edin. +::: + +:::warn +**Çok küçük `group_size`.** `group_size=2` ile GRPO'nun group-relative advantage tahmininin istatistiksel gücü yok. En az 4, kararlılık için 8+. +::: + +:::warn +**Önce SFT yok.** Base modelde GRPO nadir yararlı sonuç verir — model formatı bile çıkaramaz, neredeyse her örnek minimum reward alır. Önce format için SFT, sonra doğruluk için GRPO. +::: + +:::danger +**Reward hacking.** Model reward fonksiyonunuzdaki istem dışı pattern'leri sömürür. Sık vakalar: +- Chain-of-thought uzunluğunu ödüllendirme → model sonsuz yazar. +- Son cevabın tam-string eşleşmesini ödüllendirme → model başka şey çıkarmaz. +- "Sözdizim hatası yok"u ödüllendirme → model problemi çözmeyen trivial kod çıkarır. + +Eğitimden *önce* reward fonksiyonunuzu adversarial çıktılara karşı test edin. Format shaper yardımcı olur ama tam savunma değildir. +::: + +## Bkz. + +- [Trainer Seçimi](#/concepts/choosing-trainer) — GRPO ne zaman DPO'yu yener. +- [Otomatik Geri Alma](#/evaluation/auto-revert) — reward-hacking regresyonlarını yakala. +- [Konfigürasyon Referansı](#/reference/configuration). diff --git a/docs/usermanuals/tr/training/kto.md b/docs/usermanuals/tr/training/kto.md new file mode 100644 index 00000000..0273eb92 --- /dev/null +++ b/docs/usermanuals/tr/training/kto.md @@ -0,0 +1,88 @@ +--- +title: Kahneman-Tversky Optimization (KTO) +description: Eşli karşılaştırma değil ikili thumbs-up/down geri bildiriminden tercih hizalaması. +--- + +# Kahneman-Tversky Optimization (KTO) + +KTO, modeli ikili geri bildirim üzerinde eğitir — eşli chosen/rejected karşılaştırmaları yerine tek yanıta thumbs-up/down. Geri bildirim toplamanız tek-yanıt yargıları üretiyorsa kullanın; bu, üretimde A/B karşılaştırmasından çok daha yaygındır. + +## Ne zaman KTO + +| KTO kullan: | DPO/SimPO kullan: | +|---|---| +| Tek yanıtlara kullanıcı thumbs-up/down. | Yan yana `(chosen, rejected)` çiftleri. | +| Annotasyon bütçeniz eşli karşılaştırmaya yetmez. | Annotatörler çiftleri yan yana puanlıyor. | +| Geri bildirim üretim telemetry'sinden geliyor. | Geri bildirim labelling oturumlarından. | + +KTO'nun loss'u prospect theory üzerine kurulu — Kahneman-Tversky'nin orijinal psikoloji çalışmasının arkasındaki teori. Model, istenen yanıtların utility'sini maksimize, istenmeyenlerinkini minimize eder; eşli görmeden. + +## Hızlı örnek + +```yaml +model: + name_or_path: "./checkpoints/sft-base" + max_length: 4096 + +datasets: + - path: "data/feedback.jsonl" + format: "binary" + +training: + trainer: "kto" + epochs: 1 + learning_rate: 5.0e-7 + kto: + beta: 0.1 + desirable_weight: 1.0 + undesirable_weight: 1.0 +``` + +## Veri formatı + +```json +{"prompt": "Aboneliği nasıl iptal ederim?", "response": "Sadece ödemeyi durdur.", "label": false} +{"prompt": "Aboneliği nasıl iptal ederim?", "response": "Ayarlar → Faturalandırma…", "label": true} +``` + +KTO her iki sınıftan da örnek bekler — minimum %5-10 azınlık sınıfı. Üretim telemetry'si genelde %99 thumbs-up / %1 thumbs-down olduğundan KTO nadir sınıfta sinyal bulmakta zorlanır. + +## Parametreler + +| Parametre | Tip | Vars. | Açıklama | +|---|---|---|---| +| `beta` | float | `0.1` | KL gücü, DPO ile aynı rol. | +| `desirable_weight` | float | `1.0` | Thumbs-up satırlarını loss'ta yukarı ağırla. | +| `undesirable_weight` | float | `1.0` | Thumbs-down satırlarını yukarı ağırla. | +| `loss_type` | string | `"sigmoid"` | `sigmoid` veya `kto-pair`. | + +:::tip +**Dengesiz veri?** `undesirable_weight: 5.0` (veya dengesizliğinize uyacak oranı) ayarlayarak nadir sınıf sinyalini güçlendirin. JSONL'i over-sample etmeyin — loss ağırlıkları yapsın. +::: + +## Bellek + +~1.5× SFT belleği — DPO gibi referans tutar ama tek satırları işler. + +## KTO'nun şaşırttığı yerler + +KTO genelde gerçek-dünya thumbs-up/down telemetry'sinde DPO'dan *daha iyi* yapar; aynı veri eşlere yeniden şekillendirilmiş olsa bile. İki neden: + +1. Zorla eşleştirme spurious karşılaştırmalar yaratır — bir prompt'ta thumbs-up, farklı prompt'ta thumbs-down aynı şeyin "tercih edilen vs reddedilen"i değil. +2. Üretim telemetry'si dengesiz; KTO'nun sınıf-başı ağırlıkları bunu daha doğal işler. + +## Sık hatalar + +:::warn +**`label: 1/0`'ı `true/false` gibi muamele.** Integer değil, JSON booleanları (`true`/`false`) kullanın. KTO için integer label reddedilir. +::: + +:::warn +**Tek-sınıf veri.** Satırlarınızın %100'ü `label: true` ise KTO'nun karşı koyacak bir şey yok. Eğitim koşar ama neredeyse aynı modeli üretir. +::: + +## Bkz. + +- [DPO](#/training/dpo) — eşli tercih kuzen. +- [Dataset Formatları](#/concepts/data-formats) — `binary` formatı. +- [Trainer Seçimi](#/concepts/choosing-trainer) — karar ağacı. diff --git a/docs/usermanuals/tr/training/long-context.md b/docs/usermanuals/tr/training/long-context.md new file mode 100644 index 00000000..ac55ec7e --- /dev/null +++ b/docs/usermanuals/tr/training/long-context.md @@ -0,0 +1,140 @@ +--- +title: Uzun Bağlam Eğitimi +description: 32K-128K context penceresinde RoPE scaling, NEFTune, kayar-pencere attention ve sample packing ile eğitim. +--- + +# Uzun Bağlam Eğitimi + +Modern base modeller genelde 8K-32K yerel context ile gelir; gerçek-dünya görevleri ise sıklıkla daha fazlasını ister: kitap uzunluğunda dokümanlar, çok-dokümanlı RAG, uzun konuşmalar. ForgeLM 128K token'a kadar eğitimi (ve sürdürülen ön eğitimi) destekler. + +## Devreye giren teknikler + +```mermaid +flowchart LR + A[Base 8K context] --> B[RoPE scaling] + B --> C[Kayar-pencere
attention] + C --> D[Sample packing] + D --> E[NEFTune
regülarizasyon] + E --> F[128K-context
fine-tuned model] + classDef step fill:#1c2030,stroke:#f97316,color:#e6e7ec + classDef io fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + class A,F io + class B,C,D,E step +``` + +| Teknik | Yaptığı | +|---|---| +| **RoPE scaling** | Pozisyon embedding'lerini yeniden ölçeklendirir; model eğitilenden uzun girdileri kabul eder. | +| **Kayar-pencere attention** | Uzun dizileri bellek-verimli şekilde, üst üste binen pencerelerde işler. | +| **Sample packing** | Kısa dizileri birleştirerek her eğitim adımının context'i doldurmasını sağlar. | +| **NEFTune** | Eğitim sırasında embedding'lere gürültü ekler; uzun-context görevlerinde küçük ama tutarlı kazanımlar. | + +## Hızlı örnek + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + max_length: 32768 + rope_scaling: + type: "linear" + factor: 4.0 # 8K base × 4 = 32K + sliding_window: 4096 # 4K pencerelerde işle + load_in_4bit: true + +training: + trainer: "sft" + packing: true # throughput için kritik + neftune_noise_alpha: 5.0 # eğitim-zamanı embedding gürültüsü + +datasets: + - path: "data/long-docs.jsonl" + format: "messages" +``` + +## RoPE scaling tipleri + +| Tip | En iyi kullanım | Notlar | +|---|---|---| +| `linear` | Muhafazakar uzatma (2-4×) | Basit, iyi anlaşılan; aşırı faktörlerde hafif kalite kaybı. | +| `dynamic` | Agresif uzatma (4-8×) | Inference'ta girdi uzunluğuna göre ölçeği ayarlar. | +| `yarn` | Maksimum uzatma (8-32×) | YaRN — uç bağlamlarda en iyi kalite. >32K için önerilir. | +| `longrope` | Boyut başına ölçekleme | Per-dim ölçeği öğrenir. En esnek, en çok VRAM. | + +8K → 32K için çoğu projede `linear` ve `factor: 4.0` yeterli. 8K → 128K için `yarn` kullanın. + +## Bellek bütçesi + +Uzun-bağlam eğitimi VRAM-aç — attention dizi uzunluğunda `O(N²)`. + +| Context | 7B model VRAM (QLoRA, packing açık) | Notlar | +|---|---|---| +| 4K | 8 GB | Standart. | +| 8K | 11 GB | | +| 16K | 16 GB | Bazı modellerde kayar-pencere gerekli. | +| 32K | 24 GB | Kayar-pencere kuvvetle önerilir. | +| 64K | 40 GB+ | Çoklu-GPU bölgesi; ZeRO-3 yardımcı olur. | +| 128K | 80 GB+ | Agresif offload olmadan çok az kurulum destekler. | + +Uzun-bağlam işi göndermeden önce `forgelm --fit-check` ile teyit edin. + +## Sample packing + +Packing eğitim zamanında birkaç kısa örneği tek sabit-uzunluk diziye toplar: + +```text +Packing'siz: [örnek1] padding padding padding padding padding + [örnek2] padding padding padding padding padding + +Packing'li: [örnek1][örnek2][örnek3][örnek4][örnek5] +``` + +Çoğu örneğin `max_length`'ten çok kısa olduğu talimat-ayarı verisinde throughput %30-50 artar. SFT için kalite değişmez; ForgeLM örnek sınırları arasında loss'u otomatik maskeler. + +```yaml +training: + packing: true + packing_max_length: 32768 # genelde = max_length +``` + +:::warn +Packing örneklerin bağımsız olduğunu varsayar. Tam bağlamı koruması gereken uzun dokümanlarda (kitap bölümleri, kaynak kod repo'ları) `packing: false` ayarlayın. +::: + +## NEFTune + +Eğitim sırasında embedding'lere Gauss gürültüsü ekler. Sadeliğine rağmen uzun-bağlam genellemesini tutarlı şekilde iyileştirir: + +```yaml +training: + neftune_noise_alpha: 5.0 # alpha=5 tipik tatlı nokta +``` + +Yüksek `alpha` = daha çok regülarizasyon. 10'un üzerinde model kendisi gürültü üretmeye başlar. + +## Sık hatalar + +:::warn +**Yeniden eğitim olmadan RoPE scaling.** `rope_scaling.factor: 4.0` ayarlayıp eğitim *yapmamak* nominal context'i uzatır ama model yerel uzunluğu geçtiğinde anlamsız çıktı üretir. RoPE scaling'i etkinleştirdikten sonra (kısa süreli olsa bile) uzun-bağlam verisinde SFT yapmalısınız. +::: + +:::warn +**Tokenizer'ın context'ini uzatmayı unutmak.** Bazı tokenizer'lar orijinal context uzunluğuna sınırlanır. RoPE'u konfigüre ettikten sonra `tokenizer.model_max_length` ile doğrulayın. +::: + +:::warn +**Eğitimde değil, eval'de OOM.** Eval genelde kayar-pencere veya packing olmadan koşar — eğitim sığsa bile OOM verebilir. Gerekirse eval `max_length`'ini düşürün: +```yaml +evaluation: + max_length: 4096 # eval yerel context'te, eğitim 32K'da +``` +::: + +## Sürdürülen ön eğitim + +Agresif context uzatma (8K → 128K) için uzun dokümanlar üzerinde özel bir ön-eğitim aşaması yardımcı olur. ForgeLM ön-eğitim trainer'ı yayınlamıyor (kapsam dışı), ancak eğitilen checkpoint sonrasında uzatılmış context'te talimat-takibi için SFT-tune edilebilir. + +## Bkz. + +- [Konfigürasyon Referansı](#/reference/configuration) — her uzun-bağlam bayrağı. +- [Dağıtık Eğitim](#/training/distributed) — uzun bağlam tek GPU'yu aştığında. +- [VRAM Fit-Check](#/operations/vram-fit-check) — göndermeden önce kontrol. diff --git a/docs/usermanuals/tr/training/lora.md b/docs/usermanuals/tr/training/lora.md new file mode 100644 index 00000000..64d7d984 --- /dev/null +++ b/docs/usermanuals/tr/training/lora.md @@ -0,0 +1,144 @@ +--- +title: LoRA, QLoRA, DoRA +description: Parametre-verimli fine-tuning — ağırlıkların ~%1'ini eğit, kalitenin ~%95'ini al. +--- + +# LoRA, QLoRA, DoRA + +Low-Rank Adaptation (LoRA) ve varyantları büyük modelleri küçük GPU'larda fine-tune etmenize olanak tanır. Tüm ağırlıkları güncellemek yerine donmuş base modelin yanında düşük-rank "adapter" matrisleri eğitirsiniz — tipik olarak parametrelerin ~%1'i, VRAM'in ~%10'u, full fine-tuning'in ~%90-95 kalitesi. + +ForgeLM LoRA / QLoRA / DoRA'yı *her* trainer'a uygular (SFT, DPO, SimPO, KTO, ORPO, GRPO) — algoritmanın değil optimizer'ın özelliğidir. + +## Hangi varyantı + +```mermaid +flowchart TD + Q1{Consumer GPU'da
(<24 GB) sığmalı mı?} + Q2{Full-precision
ağırlıklar dondurulsun mu?} + Q3{LoRA maliyetinde
maksimum kalite mi?} + Full[Full fine-tuning] + LoRA([LoRA]) + QLoRA([QLoRA]) + DoRA([DoRA]) + + Q1 -->|Hayır, VRAM bol| Q2 + Q2 -->|Evet| LoRA + Q2 -->|Hayır, base eritilebilir| Full + Q1 -->|Evet| Q3 + Q3 -->|Evet| DoRA + Q3 -->|Hayır, varsayılan| QLoRA + + classDef question fill:#161a24,stroke:#0ea5e9,color:#e6e7ec + classDef result fill:#1c2030,stroke:#22c55e,color:#e6e7ec + classDef alt fill:#1c2030,stroke:#9ea3b3,color:#e6e7ec + class Q1,Q2,Q3 question + class LoRA,QLoRA,DoRA result + class Full alt +``` + +## Hızlı referans + +| Varyant | Ne değişir | VRAM (full'a göre) | Kullan | +|---|---|---|---| +| **LoRA** | Attention/MLP yanına düşük-rank matrisler | %30-40 | Full-precision base'lerde varsayılan. | +| **QLoRA** | LoRA + base'in 4-bit NF4 quantizasyonu | %10-15 | Consumer GPU varsayılanı. | +| **DoRA** | LoRA = magnitude × direction | %35-45 | LoRA maliyetinde en yüksek kalite; ~%5-10 yavaş. | +| **PiSSA** | Principal singular bileşenlerden başlatılan LoRA | %30-40 | Küçük dataset'te LoRA'dan hızlı yakınsama. | +| **rsLoRA** | Rank-stabilised scaling ile LoRA | %30-40 | Yüksek rank'larda (r ≥ 64) daha kararlı. | + +## Hızlı örnek + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true # QLoRA + bnb_4bit_quant_type: "nf4" + bnb_4bit_compute_dtype: "bfloat16" + +lora: + r: 16 + alpha: 32 + dropout: 0.05 + use_dora: false # DoRA için true + target_modules: ["q_proj", "k_proj", "v_proj", "o_proj"] + modules_to_save: [] # full-precision modüller (ör. embedding) + +training: + trainer: "sft" + learning_rate: 2.0e-4 # LoRA full FT'den yüksek LR tolere eder +``` + +## `r` rank seçimi + +Rank LoRA kalitesi için en önemli hyperparam. + +| Rank | Eğitilebilir param (7B) | Kullan | +|---|---|---| +| 4 | %0.05 | Stil transferi, sadece format. Ucuz. | +| 8 | %0.1 | Domain adaptation; küçük dataset (<5K). | +| 16 | %0.2 | **Varsayılan.** Çoğu kullanım. | +| 32 | %0.4 | Daha büyük dataset (50K+); zor görevler. | +| 64 | %0.8 | Full FT kalitesine yaklaşır. | +| 128 | %1.5 | Verim azalan; genelde full FT daha iyi. | + +`alpha` genelde rank'le ölçeklenir — `alpha = 2 × r` yaygın kural. + +## Target modules + +```yaml +lora: + target_modules: "all-linear" # en geniş — her Linear + # veya: + target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"] + # veya sadece attention: + target_modules: ["q_proj", "v_proj"] +``` + +Geniş = daha çok kapasite ama daha çok VRAM. Varsayılan (Q/K/V/O) çoğu görev için doğru denge. + +## DoRA — ne zaman değer + +DoRA her ağırlığı magnitude vektörü ve direction matrisine ayırır. Empirik: DoRA LoRA ile full fine-tuning arasındaki farkı daraltır, sıklıkla full FT kalitesini eşler. + +```yaml +lora: + r: 16 + alpha: 32 + use_dora: true +``` + +Ödünleşim: ~%5-10 yavaş eğitim ve ~%10 fazla VRAM. Kullan: +- Aksi halde full fine-tuning'e yükselmek gerekiyorsa. +- Zor görevde LoRA underfitting görüyorsanız. + +## Sık hatalar + +:::warn +**`r`'yi çok yüksek ayarlamak.** Rank 128 LoRA compute ve kalite olarak kısmi full fine-tune'a yakın — ve genelde daha küçük model + full FT daha iyi. `r > 64` sürekli geliyorsa yaklaşımı yeniden düşünün. +::: + +:::warn +**Embedding değişiklikleri için `modules_to_save` unutmak.** Tokenizer'a yeni token eklerseniz embedding ve lm_head full-precision eğitim ister: +```yaml +lora: + modules_to_save: ["embed_tokens", "lm_head"] +``` +::: + +:::warn +**Inference için yanlış base yüklemek.** QLoRA eğittiğinizde adapter full precision saklanır ama base 4-bit kalır. Inference'ta: +- Base'i 4-bit yükleyip adapter uygula, veya +- Servis için adapter'ı full-precision base'e merge edin. + +ForgeLM'in `forgelm export`'u doğru yapar. +::: + +:::tip +**Sadece adapter kaydet.** Varsayılan davranış: ForgeLM sadece adapter ağırlıklarını kaydeder (~50-200 MB) + base'i işaret eden model card. Deployment için merge: `forgelm export ./checkpoints/run --merge`. +::: + +## Bkz. + +- [GaLore](#/training/galore) — LoRA seviyesi bellekte full-parametre eğitim. +- [Konfigürasyon Referansı](#/reference/configuration) — her LoRA/quantization alanı. +- [Model Birleştirme](#/deployment/model-merging) — birden çok adapter birleştirmek. diff --git a/docs/usermanuals/tr/training/orpo.md b/docs/usermanuals/tr/training/orpo.md new file mode 100644 index 00000000..867fea53 --- /dev/null +++ b/docs/usermanuals/tr/training/orpo.md @@ -0,0 +1,82 @@ +--- +title: Odds Ratio Preference Optimization (ORPO) +description: SFT ve tercih öğrenmesini tek bir eğitim aşamasında birleştirin. +--- + +# Odds Ratio Preference Optimization (ORPO) + +ORPO, SFT ve DPO'yu tek bir eğitim geçişinde toplar. Loss, standart bir SFT terimini (`chosen` üzerinde) `rejected`'a karşı odds-ratio cezasıyla birleştirir. Sonuç: daha hızlı wall-clock, ayrı aşama yok, referans model yok. + +## Ne zaman ORPO + +| ORPO kullan: | SFT → DPO kullan: | +|---|---| +| İki yerine tek aşama istiyorsunuz. | Hizalama kararından önce SFT'yi incelemek istiyorsunuz. | +| Wall-clock zamanı önemli (CI/CD gece koşusu). | Tercih verisi üzerinde SFT'den çok yineleyeceksiniz. | +| Hem çiftler hem temiz SFT verisi hazır. | Sadece SFT verisi var, tercihler sonra gelecek. | +| Base modelden başlıyorsunuz. | Zaten SFT eğitilmiş modeli hizalıyorsunuz. | + +:::tip +ORPO, base modelden *direkt* iyi çalışan tek hizalama yöntemidir — kendi SFT terimini içerir. +::: + +## Hızlı örnek + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true + +datasets: + - path: "data/preferences.jsonl" + format: "preference" + +training: + trainer: "orpo" + epochs: 1 + batch_size: 2 + learning_rate: 5.0e-6 + orpo: + beta: 0.1 +``` + +## Veri formatı + +`preference` formatı: `prompt`, `chosen`, `rejected`. ORPO'nun SFT terimi `chosen` üzerinde eğitir; odds-ratio terimi `rejected`'ı cezalandırır. + +## Parametreler + +| Parametre | Tip | Vars. | Açıklama | +|---|---|---|---| +| `beta` | float | `0.1` | Odds-ratio ceza terimi gücü. Yüksek = çok tercih kayması. | +| `loss_type` | string | `"sigmoid"` | Şu an sadece `sigmoid`. | +| `sft_weight` | float | `1.0` | Birleşik loss'ta SFT teriminin ağırlığı. | + +## Bellek + +~1.5× SFT belleği — referans model gerekmez (DPO'nun aksine), ama loss her satır için hem `chosen` hem `rejected`'ı işler. + +## ORPO'nun zorlandığı yerler + +| Durum | Neden | +|---|---| +| Çok küçük tercih dataset (<2K satır) | Birleşik loss ayrı SFT+DPO'dan çok veri gerek | +| Tercih çiftleri arası kalite çok değişken | Birleşik gradient gürültülü | +| Hizalamadan önce SFT çıktılarını incelemek gerek | ORPO ara SFT checkpoint'i üretmez | + +Bu durumlarda SFT ve DPO'yu ayrı çalıştırın. + +## Sık hatalar + +:::warn +**Zaten SFT eğitilmiş modelde ORPO.** ORPO'nun SFT terimi modeli `chosen` yanıtlarda eğitmeye devam eder — istediğiniz buysa tamam, ama "SFT checkpoint'imin üstüne sadece DPO" istiyorsanız [DPO](#/training/dpo) kullanın. +::: + +:::warn +**`beta`'yı çok yüksek ayarlama.** Çok yüksek `beta` SFT terimini bastırır — sonuçta "karşılaştırmayı kazanan" ama yararlı olmayan bozuk format çıktılar üretir. +::: + +## Bkz. + +- [SFT](#/training/sft) ve [DPO](#/training/dpo) — ORPO'nun sıkıştırdığı iki aşama. +- [Konfigürasyon Referansı](#/reference/configuration). diff --git a/docs/usermanuals/tr/training/sft.md b/docs/usermanuals/tr/training/sft.md new file mode 100644 index 00000000..147d54e3 --- /dev/null +++ b/docs/usermanuals/tr/training/sft.md @@ -0,0 +1,124 @@ +--- +title: Denetimli Fine-Tuning (SFT) +description: Her alignment hattının temeli — base modeli talimat çiftleri üzerinde eğitin. +--- + +# Denetimli Fine-Tuning (SFT) + +SFT, post-training'in iş atıdır. Modele doğru çıktıların örneklerini verirsiniz, deseni öğrenir. Neredeyse her proje burada başlar; sonu DPO veya GRPO olsa bile. + +## Ne zaman SFT + +| SFT kullan: | SFT kullanma: | +|---|---| +| Prompt-completion çifti var (en sık şekil). | Sadece tercih çifti var. Doğrudan [DPO](#/training/dpo) (ama aşağıdaki uyarı). | +| Base modelden başlıyorsunuz, format öğretmek gerek. | Zaten SFT eğittiniz; sadece tercih hizalaması gerekli. | +| Basit, kararlı, iyi anlaşılan dinamik istiyorsunuz. | RL stili reward optimizasyonu gerek. [GRPO](#/training/grpo). | + +:::tip +Önce SFT, neredeyse her zaman. Zengin tercih verisi olan ekipler bile DPO/SimPO/KTO'dan önce SFT yapar — base modele direkt tercih öğrenme kararsız, formatı bozuk çıktı üretir. +::: + +## Hızlı örnek + +```yaml +model: + name_or_path: "Qwen/Qwen2.5-7B-Instruct" + load_in_4bit: true + max_length: 4096 + +lora: + r: 16 + alpha: 32 + +datasets: + - path: "data/train.jsonl" + format: "messages" + +training: + trainer: "sft" + epochs: 3 + batch_size: 4 + learning_rate: 2.0e-4 + warmup_ratio: 0.03 + scheduler: "cosine" + +output: + dir: "./checkpoints/sft" +``` + +```shell +$ forgelm --config configs/sft.yaml --dry-run +$ forgelm --config configs/sft.yaml +``` + +## Veri formatı + +İki format desteklenir. Detay için bkz. [Dataset Formatları](#/concepts/data-formats). + +**Tek-tur `instructions`:** +```json +{"prompt": "Fransızcaya çevir: 'Good morning'.", "completion": "Bonjour."} +``` + +**Multi-turn `messages`:** +```json +{"messages": [ + {"role": "user", "content": "..."}, + {"role": "assistant", "content": "..."} +]} +``` + +## Konfigürasyon parametreleri + +SFT-özgü ayarlar standart `training` bloğuyla yan yanadır. + +| Parametre | Tip | Vars. | Açıklama | +|---|---|---|---| +| `learning_rate` | float | `2e-4` | LoRA: 1e-4 - 5e-4. Full-parametre: 1e-5 - 5e-5. | +| `epochs` | int | `3` | Daha çok = daha çok ezberleme, daha az genelleme. | +| `batch_size` | int | `4` | Cihaz başına. Etkili batch için gradient accumulation ile çarpın. | +| `max_length` | int | `4096` | Eğitimdeki context. Uzun = çok VRAM. | +| `packing` | bool | `false` | Kısa dizileri throughput için paketle. %30-50 hız. | +| `neftune_noise_alpha` | float | `null` | Embedding-noise regülarizasyonu. Küçük dataset'lerde `5.0` iyileştirir. | +| `loss_on_completions_only` | bool | `true` | Sadece assistant token'larında loss hesapla. Önerilir. | + +Tam parametre listesi: [Konfigürasyon Referansı](#/reference/configuration). + +## Compute ve bellek + +SFT bellek olarak en hafif post-training paradigmasıdır: + +| Model | LoRA rank | `max_length` | Yaklaşık VRAM (QLoRA 4-bit) | +|---|---|---|---| +| 7B | 16 | 4096 | 8 GB | +| 13B | 16 | 4096 | 14 GB | +| 8B Llama 3 | 32 | 8192 | 16 GB | +| 70B | 16 | 2048 | 2× A100 + ZeRO gerekir | + +Her zaman göndermeden önce `--fit-check` koşturun. + +## Sık yapılan hatalar + +:::warn +**Full fine-tune için çok yüksek learning rate.** 2e-4 LoRA'da çalışır ama full-parametre koşusunu eritir. Full FT için 1e-5 - 5e-5'e düşürün. +::: + +:::warn +**Loss düşmek yerine artıyor.** Muhtemelen tokenizer uyuşmazlığı — veriniz modelin tokenizer'ındaki chat template'tan farklı format için. `forgelm audit` koşturun ve audit raporundaki render edilmiş örnekleri kontrol edin. +::: + +:::warn +**`loss_on_completions_only` etkinleştirmeyi unutmak.** Devre dışıyken model kapasiteyi prompt'u tekrarlamayı öğrenmekle harcar. Varsayılan `true`; sadece olağandışı eğitim-objesi deneyleri için kapatın. +::: + +:::tip +**Sample packing dramatik hızlandırır.** Ortalama örneğiniz `max_length`'ten çok kısaysa `packing: true` ayarlayın — kısa örnekleri tek diziye paketler, %30-50 throughput. Talimat ayarı için kalite farkı yok. +::: + +## Bkz. + +- [DPO](#/training/dpo) — SFT'den sonra olağan adım. +- [LoRA, QLoRA, DoRA](#/training/lora) — parametre-verimli SFT. +- [Veri Seti Denetimi](#/data/audit) — SFT'den önce daima. +- [Konfigürasyon Referansı](#/reference/configuration) — tüm eğitim parametreleri. diff --git a/docs/usermanuals/tr/training/simpo.md b/docs/usermanuals/tr/training/simpo.md new file mode 100644 index 00000000..5d497c6e --- /dev/null +++ b/docs/usermanuals/tr/training/simpo.md @@ -0,0 +1,91 @@ +--- +title: Simple Preference Optimization (SimPO) +description: Referans modelsiz tercih öğrenmesi — bellekte ikinci model olmadan DPO. +--- + +# Simple Preference Optimization (SimPO) + +SimPO, DPO'nun sadeleştirilmiş kuzenidir; referans modeli denklemden çıkarır. Ödünleşim: yaklaşık yarı VRAM, biraz daha az kararlılık. + +## Ne zaman SimPO + +| SimPO kullan: | DPO tercih et: | +|---|---| +| VRAM bütçesi dar (ör. tek 24 GB GPU'da 13B+). | İkinci modeli bellekte tutabiliyorsanız. | +| Temiz referans checkpoint'iniz yok. | SFT checkpoint'iniz yüksek kalite ve güvenilir. | +| Daha basit eğitim dinamiği istiyorsanız. | Kararlılık VRAM'den önemliyse. | + +:::tip +Pratik kural: [`--fit-check`](#/operations/vram-fit-check) DPO için `OOM` raporlarsa, daha küçük model veya kısa context düşünmeden önce SimPO'ya geçin. Standart benchmark'larda kalite farkı genelde %5'in altındadır. +::: + +## Hızlı örnek + +```yaml +model: + name_or_path: "./checkpoints/sft-base" + max_length: 4096 + +datasets: + - path: "data/preferences.jsonl" + format: "preference" + +training: + trainer: "simpo" + epochs: 1 + learning_rate: 8.0e-7 + simpo: + beta: 2.0 # DPO'nun 0.1'inden farklı + gamma: 1.0 # margin terimi + loss_type: "sigmoid" + +output: + dir: "./checkpoints/simpo" +``` + +## Parametreler + +| Parametre | Tip | Vars. | Açıklama | +|---|---|---|---| +| `beta` | float | `2.0` | Uzunluk-normalize ödül ölçeği. Yüksek = güçlü tercih kayması. **DPO beta ile aynı ölçek değil.** | +| `gamma` | float | `1.0` | Margin — chosen ve rejected log-likelihood arasında SimPO'nun korumaya çalıştığı boşluk. | +| `loss_type` | string | `"sigmoid"` | `sigmoid` veya `hinge`. | +| `length_normalize` | bool | `true` | Log-prob'ları dizi uzunluğuna normalize et. SimPO'nun imza özelliği. | +| `label_smoothing` | float | `0.0` | Gürültülü veride yumuşatma. | + +## Bellek + +~1.2× SFT belleği — DPO'nun 2×'inden çok daha hafif. + +| Model | LoRA rank | `max_length` | VRAM (QLoRA 4-bit) | +|---|---|---|---| +| 7B | 16 | 4096 | 9 GB | +| 13B | 16 | 4096 | 16 GB | + +## `beta` ve `gamma` + +| Kombinasyon | Davranış | +|---|---| +| `beta=2.0`, `gamma=1.0` | Varsayılan. Dengeli. | +| `beta=2.5`, `gamma=1.4` | Daha agresif tercih kayması. | +| `beta=1.5`, `gamma=0.5` | Daha yumuşak, orijinal SFT çıktılarına yakın. | + +:::warn +SimPO'nun `beta`'sı DPO'nun `beta`'sından farklı ölçekte. DPO hyperparam'larını kopyalamayın — SimPO varsayılanlarından başlayın. +::: + +## Sık hatalar + +:::warn +**Beta'da aşırıya kaçma.** SimPO DPO'dan daha duyarlıdır; yüksek `beta` + küçük dataset chosen'ı agresif tercih eden ama genel yetenek kaybeden model üretir. Eğitim sırasında benchmark puanlarınızı izleyin. +::: + +:::warn +**SFT'siz SimPO.** DPO ile aynı uyarı — kaliteli SFT checkpoint'ten başlayın, ham base modelden değil. +::: + +## Bkz. + +- [DPO](#/training/dpo) — referans-tabanlı kuzen. +- [ORPO](#/training/orpo) — SFT ve tercih kaybını tek aşamada. +- [Konfigürasyon Referansı](#/reference/configuration). diff --git a/site/compliance.html b/site/compliance.html index e7d320b9..55c4585c 100644 --- a/site/compliance.html +++ b/site/compliance.html @@ -3,14 +3,12 @@ - Compliance — ForgeLM - Compliance — ForgeLM + - - + + @@ -21,6 +19,7 @@ + @@ -31,17 +30,32 @@ ForgeLM - + + @@ -51,18 +65,9 @@ @@ -70,100 +75,73 @@

- - Article-by-article mapping - Madde-madde eşleme - -

- Where each obligation lives in the code - Her yükümlülüğün kodda nerede yaşadığı -

-

- Each card maps a Regulation (EU) 2024/1689 article to the ForgeLM module that fulfils it. Open the GitHub link to see the implementation. - Her kart, Regulation (EU) 2024/1689 maddesini onu yerine getiren ForgeLM modülüne eşler. Uygulamayı görmek için GitHub linkini açın. -

+ Article-by-article mapping +

Where each obligation lives in the code

+

Each card maps a Regulation (EU) 2024/1689 article to the ForgeLM module that fulfils it.

Article 9 -

Risk managementRisk yönetimi

-

A continuous, iterative process: identify foreseeable risks, evaluate, mitigate. Auto-revert on threshold breach is the technical mitigation; trend tracking is the monitoring loop.Sürekli, iteratif süreç: öngörülebilir riskleri tanımla, değerlendir, azalt. Eşik aşımında otomatik geri alma teknik mitigasyon; trend izleme monitoring döngüsü.

-
- forgelm/safety.py · forgelm/compliance.py -
+

Risk management

+

A continuous, iterative process: identify foreseeable risks, evaluate, mitigate.

+
forgelm/safety.py · forgelm/compliance.py
Article 10 -

Data & data governanceVeri ve veri yönetimi

-

Quality, relevance, representativeness criteria. Bias detection, PII redaction, cross-split leakage gate. Every audit report becomes a Article 10 evidence document.Kalite, uygunluk, temsiliyet kriterleri. Bias tespiti, PII redaksiyonu, split-arası sızıntı kapısı. Her audit raporu Madde 10 kanıt belgesi olur.

-
- forgelm/data_audit.py · forgelm/ingestion.py -
+

Data & data governance

+

Quality, relevance, representativeness criteria. Bias detection, PII redaction.

+
forgelm/data_audit.py · forgelm/ingestion.py
Article 11 -

Technical documentationTeknik dokümantasyon

-

Annex IV's eight required sections — auto-populated from the run: general description, detailed system, monitoring, risk management, lifecycle, standards, declaration, post-market.Annex IV'ün sekiz zorunlu bölümü — koşudan otomatik doldurulur: genel açıklama, detay sistem, izleme, risk yönetimi, yaşam döngüsü, standartlar, beyan, post-market.

-
- artifacts/annex_iv.json -
+

Technical documentation

+

Annex IV's eight required sections — auto-populated from the run.

+
artifacts/annex_iv.json
Article 12 -

Record-keeping (logs)Kayıt tutma (loglar)

-

Append-only event log over training start, eval gates, auto-revert decisions, model export. SHA-256 over each artifact for tamper-evidence.Eğitim başlangıcı, eval kapıları, otomatik geri alma kararları, model export üzerinde append-only event log. Her artifact üzerinde tamper-evidence için SHA-256.

-
- forgelm/compliance.py · artifacts/audit_log.jsonl -
+

Record-keeping (logs)

+

Append-only event log over training start, eval gates, auto-revert decisions.

+
forgelm/compliance.py · artifacts/audit_log.jsonl
Article 13 -

TransparencyŞeffaflık

-

Auto-generated model card lists capabilities, intended use, training data summary, evaluation results, known limitations. Drop-in for HuggingFace Hub README.Otomatik üretilen model card; yetenekleri, amaçlanan kullanımı, eğitim veri özetini, değerlendirme sonuçlarını, bilinen sınırlamaları listeler. HuggingFace Hub README için drop-in.

-
- --model-card · output_dir/README.md -
+

Transparency

+

Auto-generated model card lists capabilities, intended use, training data summary.

+
--model-card · output_dir/README.md
Article 14 -

Human oversightİnsan gözetimi

-

Optional compliance.human_approval: true blocks model promotion until a human signs off. Webhook to your incident tool; signed approval lands in the audit log.Opsiyonel compliance.human_approval: true bir insan onaylayana kadar model promosyonunu durdurur. Incident aracınıza webhook; imzalı onay audit log'a düşer.

-
- compliance.human_approval -
+

Human oversight

+

Optional compliance.human_approval: true blocks model promotion until a human signs off.

+
compliance.human_approval
Article 15 -

Accuracy & robustnessDoğruluk ve sağlamlık

-

Benchmark gates per-task floor; if the post-train number drops below the floor, the run fails (exit 3). Cybersecurity: secrets / PII at ingest, dependency CVE awareness.Görev başı taban için benchmark kapısı; post-train sayısı tabanın altına düşerse koşu başarısız (exit 3). Siber güvenlik: ingest'te sırlar / PII, bağımlılık CVE farkındalığı.

-
- forgelm/benchmark.py -
+

Accuracy & robustness

+

Benchmark gates per-task floor; if the post-train number drops below the floor, the run fails (exit 3).

+
forgelm/benchmark.py
Article 16-17 -

Conformity & QMSUygunluk ve QMS

-

QMS SOPs in docs/qms/ cover release, incident response, data-source onboarding. Conformity declaration template generated from the run's Annex IV.docs/qms/'deki QMS SOP'ları sürüm yönetimi, incident response, veri kaynağı onboarding'i kapsar. Uygunluk beyanı şablonu koşunun Annex IV'ünden üretilir.

-
- docs/qms/ -
+

Conformity & QMS

+

QMS SOPs in docs/qms/ cover release, incident response, data-source onboarding.

+
docs/qms/
GDPR -

PII redaction at ingestIngest'te PII redaksiyonu

-

--pii-mask redacts emails, phones, credit cards (Luhn), IBAN, national IDs (TR/DE/FR/US-SSN) before chunks land in JSONL — Article 5(1)(c) data minimisation enforced upstream.--pii-mask chunk'lar JSONL'a düşmeden e-posta, telefon, kredi kartı (Luhn), IBAN, ulusal kimlik (TR/DE/FR/US-SSN) maskeler — Madde 5(1)(c) data minimisation upstream'de uygulanır.

-
- forgelm/data_audit.py::mask_pii -
+

PII redaction at ingest

+

--pii-mask redacts emails, phones, credit cards, IBAN, national IDs before chunks land in JSONL.

+
forgelm/data_audit.py::mask_pii
@@ -173,25 +151,16 @@

PII redaction at ingest
- - What you get on disk - Diskte ne elde edersiniz - -

- A run's compliance footprint - Bir koşunun uyumluluk ayak izi -

-

- After every successful (or failed) run, this is what lands in your output directory. - Her başarılı (veya başarısız) koşudan sonra çıktı dizininize bunlar düşer. -

+ What you get on disk +

A run's compliance footprint

+

After every successful (or failed) run, this is what lands in your output directory.

checkpoints/policy-bot/ - +
artifacts/
 ├── annex_iv.json              # Article 11 technical documentation
@@ -214,38 +183,17 @@ 

- - Honest limits - Dürüst sınırlar - -

- What ForgeLM does not claim - ForgeLM'in iddia etmediği şeyler -

+ Honest limits +

What ForgeLM does not claim

@@ -254,23 +202,11 @@

-

- Want a deeper look? - Daha derin bir bakış ister misiniz? -

-

- The compliance module, audit log schema, and Annex IV generator are all in forgelm/compliance.py. Read the source — it's the most honest documentation we ship. - Uyumluluk modülü, audit log şeması ve Annex IV jeneratörünün hepsi forgelm/compliance.py'da. Kaynağı okuyun — gönderdiğimiz en dürüst dokümantasyon. -

+

Want a deeper look?

+

The compliance module, audit log schema, and Annex IV generator are all in forgelm/compliance.py.

@@ -281,10 +217,10 @@

diff --git a/site/contact.html b/site/contact.html index 98efdc38..6ea472a1 100644 --- a/site/contact.html +++ b/site/contact.html @@ -3,14 +3,12 @@ - Contact — ForgeLM - Contact — ForgeLM + - - + + @@ -21,6 +19,7 @@ + @@ -31,17 +30,32 @@ ForgeLM - + + @@ -51,18 +65,9 @@ @@ -72,73 +77,62 @@

-

- Send a message - Mesaj gönderin -

-

- Routed via Formspree. Your email is only used to reply — no list, no tracking. - Formspree üzerinden iletilir. E-postanız yalnızca cevap için kullanılır — liste yok, takip yok. -

- - +

Send a message

+

Routed via Formspree.

+
- +
- +
- +
- +
- +
- +
- +
-

- Other channels - Diğer kanallar -

+

Other channels

  • @@ -147,14 +141,8 @@

GitHub Issues

-

- Reproducible bug? File an issue with config + log excerpt — the team triages within 48 hours. - Tekrarlanabilir hata mı? Config + log alıntısıyla bir issue açın — ekip 48 saat içinde triage eder. -

- - Open an issue → - Issue aç → - +

Reproducible bug? File an issue with config + log excerpt.

+ Open an issue →
@@ -164,14 +152,8 @@

GitHub Issues

GitHub Discussions

-

- Open-ended questions, design ideas, or "is this the right tool for X" — discuss with the community. - Açık uçlu sorular, tasarım fikirleri veya "X için doğru araç mı" — toplulukla tartışın. -

- - Join the conversation → - Tartışmaya katıl → - +

Open-ended questions, design ideas — discuss with the community.

+ Join the conversation →
@@ -180,14 +162,8 @@

GitHub Discussions

-

- Security disclosure - Güvenlik açıklaması -

-

- Found a vulnerability? Use the form on the left with topic Security disclosure. We acknowledge within 72 hours and respect responsible-disclosure timelines. - Bir güvenlik açığı mı buldunuz? Soldaki formu Security disclosure konusuyla kullanın. 72 saat içinde teyit ederiz ve sorumlu-açıklama takvimine saygı duyarız. -

+

Security disclosure

+

Found a vulnerability? Use the form on the left with topic Security disclosure.

@@ -196,18 +172,9 @@

-

- Contribute - Katkıda bulun -

-

- PRs welcome. Read CONTRIBUTING.md for the standards (especially the regex hygiene rules and the bilingual docs convention). - PR'lar memnuniyetle. Standartlar için CONTRIBUTING.md'yi okuyun (özellikle regex hijyeni kuralları ve bilingual docs konvansiyonu). -

- - Read the guide → - Rehberi oku → - +

Contribute

+

PRs welcome. Read CONTRIBUTING.md for the standards.

+ Read the guide →
@@ -221,9 +188,9 @@

diff --git a/site/css/style.css b/site/css/style.css index 5dfb92b0..882e5251 100644 --- a/site/css/style.css +++ b/site/css/style.css @@ -1337,13 +1337,15 @@ section { padding: 5rem 0; } } /* ── i18n ────────────────────────────────────────────────── */ -/* Translations are applied at runtime by js/i18n.js, which replaces - text content for elements carrying [data-i18n], [data-i18n-html] or - [data-i18n-attr] attributes. No display toggling required. - Hide elements until i18n.js has run, so users do not see English - defaults flicker if their preferred language is something else. */ -html:not([lang]) [data-i18n], -html:not([lang]) [data-i18n-html] { visibility: hidden; } +/* Translations are applied at runtime by js/i18n.js. To prevent a flash + of English defaults for users on other languages, the body stays + visually muted until i18n.js applies the table and adds the + `i18n-ready` class. Falls back gracefully if JS is disabled + (after 800ms the body is forced visible). */ +body:not(.i18n-ready) [data-i18n], +body:not(.i18n-ready) [data-i18n-html] { visibility: hidden; } +body:not(.i18n-ready) { animation: i18n-failsafe 0.8s linear forwards; } +@keyframes i18n-failsafe { to { visibility: visible; } } /* ── Accessibility ──────────────────────────────────────── */ @media (prefers-reduced-motion: reduce) { @@ -1399,3 +1401,673 @@ html:not([lang]) [data-i18n-html] { visibility: hidden; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 4px; } ::-webkit-scrollbar-thumb:hover { background: var(--text-muted); } + +/* =============================================================== + USER GUIDE — sidebar + content + on-this-page TOC layout. + The shell lives in site/guide.html; content is loaded at runtime + from site/js/usermanuals/.js (built from docs/usermanuals/). + =============================================================== */ + +/* Reading-progress bar at the top of the viewport */ +.guide-progress { + position: fixed; + top: 0; left: 0; + height: 2px; + width: 0%; + background: linear-gradient(90deg, var(--ember), var(--steel)); + z-index: 200; + transition: width 0.08s linear; + pointer-events: none; +} + +/* The 3-column shell. Padding-top accounts for the fixed 64px navbar. */ +.guide-layout { + display: grid; + grid-template-columns: 260px minmax(0, 1fr) 220px; + gap: 2.5rem; + max-width: 1280px; + margin: 0 auto; + padding: 5.5rem 1.5rem 3rem; +} + +@media (max-width: 1100px) { + .guide-layout { grid-template-columns: 230px minmax(0, 1fr); gap: 2rem; } + .guide-toc { display: none; } +} + +@media (max-width: 880px) { + .guide-layout { grid-template-columns: 1fr; padding: 5rem 1rem 2rem; } + .guide-sidebar { display: none; } + .guide-sidebar.open { display: block; } +} + +/* ── Sidebar (sections + pages) ─────────────────────────── */ +.guide-sidebar { + position: sticky; + top: calc(64px + 1.5rem); + align-self: start; + max-height: calc(100vh - 64px - 3rem); + overflow-y: auto; + padding-right: 0.5rem; +} + +.guide-sidebar-search { + width: 100%; + background: var(--bg-elev); + border: 1px solid var(--border); + color: var(--text); + border-radius: var(--radius-sm); + padding: 0.55rem 0.75rem 0.55rem 2rem; + font: 500 0.85rem var(--font-sans); + margin-bottom: 1.25rem; + position: relative; + background-image: + url("data:image/svg+xml;utf8,"); + background-repeat: no-repeat; + background-position: 0.6rem center; + outline: none; + transition: border-color var(--transition); +} +.guide-sidebar-search:focus { border-color: var(--ember); } +.guide-sidebar-search::placeholder { color: var(--text-muted); } + +.guide-sidebar-kbd { + position: absolute; + right: 0.75rem; + top: 50%; + transform: translateY(-50%); + font: 600 0.7rem var(--font-mono); + color: var(--text-muted); + background: var(--bg); + border: 1px solid var(--border); + border-radius: 4px; + padding: 1px 5px; + pointer-events: none; +} +.guide-sidebar-search-wrap { position: relative; } + +.guide-nav-section { margin-bottom: 1.4rem; } +.guide-nav-section h4 { + font: 700 0.7rem var(--font-sans); + text-transform: uppercase; + letter-spacing: 0.1em; + color: var(--text-muted); + margin-bottom: 0.55rem; + padding: 0 0.6rem; +} +.guide-nav-section ul { list-style: none; padding: 0; } +.guide-nav-section li { margin: 0; } +.guide-nav-section a { + display: block; + padding: 0.4rem 0.7rem; + font-size: 0.88rem; + color: var(--text-secondary); + border-radius: var(--radius-sm); + border-left: 2px solid transparent; + margin-left: -2px; + transition: all 0.15s ease; + line-height: 1.4; +} +.guide-nav-section a:hover { + color: var(--text); + background: var(--bg-elev); +} +.guide-nav-section a.active { + color: var(--ember-bright); + border-left-color: var(--ember); + background: rgba(249,115,22,.08); + font-weight: 500; +} +.guide-nav-section a.fallback::after { + content: '·'; + color: var(--warn); + margin-left: 0.4rem; + font-weight: bold; +} + +/* ── Content area ───────────────────────────────────────── */ +.guide-content { + min-width: 0; + max-width: 760px; +} + +.guide-breadcrumb { + display: flex; + align-items: center; + gap: 0.4rem; + font-size: 0.82rem; + color: var(--text-muted); + margin-bottom: 1.25rem; + flex-wrap: wrap; +} +.guide-breadcrumb a { + color: var(--text-muted); + transition: color var(--transition); +} +.guide-breadcrumb a:hover { color: var(--ember-bright); } +.guide-breadcrumb svg { + width: 12px; height: 12px; + opacity: 0.6; +} +.guide-breadcrumb .current { color: var(--text); } + +.guide-fallback-banner { + display: flex; + align-items: flex-start; + gap: 0.7rem; + padding: 0.85rem 1rem; + background: rgba(234,179,8,.06); + border: 1px solid rgba(234,179,8,.25); + border-radius: var(--radius-sm); + font-size: 0.88rem; + color: var(--text-secondary); + margin-bottom: 1.5rem; +} +.guide-fallback-banner svg { + width: 18px; height: 18px; + color: var(--warn); + flex-shrink: 0; + margin-top: 1px; +} + +.guide-content h1 { + font-size: clamp(1.85rem, 3vw, 2.4rem); + line-height: 1.2; + margin-bottom: 0.6rem; + letter-spacing: -0.025em; +} +.guide-content > p:first-of-type, +.guide-content .guide-page-description { + font-size: 1.08rem; + color: var(--text-secondary); + line-height: 1.65; + margin-bottom: 2.2rem; +} + +.guide-content h2 { + font-size: 1.45rem; + margin: 2.5rem 0 0.9rem; + padding-top: 0.4rem; + scroll-margin-top: 80px; + position: relative; +} +.guide-content h3 { + font-size: 1.12rem; + margin: 1.8rem 0 0.7rem; + scroll-margin-top: 80px; +} +.guide-content h4 { + font-size: 0.95rem; + margin: 1.4rem 0 0.5rem; + color: var(--text); +} + +/* anchor link icon on hover */ +.guide-content h2::before, .guide-content h3::before { + content: '#'; + position: absolute; + left: -1.2rem; + color: var(--text-muted); + opacity: 0; + transition: opacity var(--transition); + font-weight: 400; +} +.guide-content h2:hover::before, .guide-content h3:hover::before { + opacity: 0.5; +} + +.guide-content p { + margin: 0.85rem 0; + line-height: 1.75; +} +.guide-content ul, .guide-content ol { + margin: 0.85rem 0 0.85rem 1.4rem; + color: var(--text-secondary); + line-height: 1.75; +} +.guide-content li { margin-bottom: 0.4rem; } +.guide-content li > p { margin: 0.3rem 0; } +.guide-content strong { color: var(--text); font-weight: 600; } + +.guide-content > pre, +.guide-content > .codehilite, +.guide-content > .code-block { + margin: 1.2rem 0; +} + +/* Tables (parameter references) */ +.guide-content table { + width: 100%; + margin: 1.4rem 0; + border-collapse: collapse; + font-size: 0.88rem; + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + overflow: hidden; +} +.guide-content thead { + background: var(--bg-elev); +} +.guide-content th { + text-align: left; + padding: 0.65rem 0.85rem; + font-weight: 600; + font-size: 0.78rem; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--text-muted); + border-bottom: 1px solid var(--border-strong); +} +.guide-content td { + padding: 0.65rem 0.85rem; + border-top: 1px solid var(--border); + vertical-align: top; + color: var(--text-secondary); + line-height: 1.55; +} +.guide-content tbody tr:hover { + background: rgba(255,255,255,0.015); +} +.guide-content td code, +.guide-content th code { + font-size: 0.82em; + white-space: nowrap; +} +.guide-content td:first-child code { + color: var(--steel-bright); +} + +/* Code blocks (markdown-rendered) */ +.guide-content pre { + background: var(--code-bg); + border: 1px solid var(--code-border); + border-radius: var(--radius); + padding: 1rem 1.2rem; + font-family: var(--font-mono); + font-size: 0.85rem; + line-height: 1.65; + color: var(--code-text); + overflow-x: auto; +} +.guide-content pre code { background: none; border: none; padding: 0; color: inherit; font-size: inherit; } + +/* Inline code in content (matches existing) */ +.guide-content :not(pre) > code { + background: var(--bg-elev); + border: 1px solid var(--border); + padding: 0.12em 0.4em; + border-radius: 4px; + color: var(--ember-bright); + font-size: 0.85em; +} + +.guide-content blockquote { + margin: 1.2rem 0; + padding: 0.5rem 1rem; + border-left: 3px solid var(--border-strong); + color: var(--text-secondary); + font-style: italic; +} + +/* ── Callouts ────────────────────────────────────────────── */ +.callout { + display: block; + margin: 1.4rem 0; + padding: 0.85rem 1.1rem; + border-radius: var(--radius-sm); + border-left: 3px solid; + position: relative; + font-size: 0.92rem; + line-height: 1.65; +} +.callout > p:first-child { margin-top: 0; padding-left: 1.7rem; } +.callout > p { margin: 0.5rem 0; } +.callout > p:last-child { margin-bottom: 0; } +.callout > p:first-child::before { + content: ''; + position: absolute; + left: 1rem; + top: 1rem; + width: 18px; + height: 18px; + background-repeat: no-repeat; + background-position: center; + background-size: 18px 18px; +} +.callout ul, .callout ol { margin: 0.4rem 0 0.4rem 1.4rem; } + +.callout-note { + background: rgba(14,165,233,.06); + border-color: var(--steel); + color: var(--text-secondary); +} +.callout-note > p:first-child::before { + background-image: url("data:image/svg+xml;utf8,"); +} + +.callout-tip { + background: rgba(34,197,94,.06); + border-color: var(--success); + color: var(--text-secondary); +} +.callout-tip > p:first-child::before { + background-image: url("data:image/svg+xml;utf8,"); +} + +.callout-warn { + background: rgba(234,179,8,.06); + border-color: var(--warn); + color: var(--text-secondary); +} +.callout-warn > p:first-child::before { + background-image: url("data:image/svg+xml;utf8,"); +} + +.callout-danger { + background: rgba(239,68,68,.06); + border-color: var(--danger); + color: var(--text-secondary); +} +.callout-danger > p:first-child::before { + background-image: url("data:image/svg+xml;utf8,"); +} + +.callout-info { + background: rgba(192,132,252,.06); + border-color: var(--code-fn); + color: var(--text-secondary); +} +.callout-info > p:first-child::before { + background-image: url("data:image/svg+xml;utf8,"); +} + +.callout-pill { + display: inline-block; + font-size: 0.7rem; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.06em; + padding: 1px 6px; + border-radius: 3px; + border: 1px solid; +} +.callout-pill.note { color: var(--steel-bright); border-color: var(--steel); background: rgba(14,165,233,.1); } +.callout-pill.tip { color: #4ade80; border-color: var(--success); background: rgba(34,197,94,.1); } +.callout-pill.warn { color: #facc15; border-color: var(--warn); background: rgba(234,179,8,.1); } +.callout-pill.danger { color: #f87171; border-color: var(--danger); background: rgba(239,68,68,.1); } + +/* ── Mermaid diagrams ────────────────────────────────────── */ +.guide-content .mermaid { + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 1.2rem 1rem; + margin: 1.4rem 0; + text-align: center; + overflow-x: auto; +} +.guide-content .mermaid svg { max-width: 100%; height: auto; margin: 0 auto; } + +/* ── Prev / Next pager ──────────────────────────────────── */ +.guide-pager { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0.8rem; + margin: 3rem 0 1rem; +} +.guide-pager-card { + display: flex; + flex-direction: column; + gap: 0.3rem; + padding: 0.95rem 1.1rem; + border: 1px solid var(--border); + border-radius: var(--radius-sm); + background: var(--bg-card); + transition: all var(--transition); + text-decoration: none !important; + min-height: 70px; +} +.guide-pager-card:hover { + border-color: var(--ember); + background: var(--bg-elev); + transform: translateY(-1px); +} +.guide-pager-card.next { text-align: right; align-items: flex-end; } +.guide-pager-card .label { + font-size: 0.74rem; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--text-muted); + font-weight: 600; +} +.guide-pager-card .title { + font-size: 0.95rem; + font-weight: 600; + color: var(--text); +} +.guide-pager-card.placeholder { + visibility: hidden; +} +@media (max-width: 600px) { + .guide-pager { grid-template-columns: 1fr; } +} + +/* ── On-this-page TOC ────────────────────────────────────── */ +.guide-toc { + position: sticky; + top: calc(64px + 1.5rem); + align-self: start; + max-height: calc(100vh - 64px - 3rem); + overflow-y: auto; + padding-left: 1rem; + border-left: 1px solid var(--border); +} +.guide-toc-title { + font: 700 0.72rem var(--font-sans); + text-transform: uppercase; + letter-spacing: 0.1em; + color: var(--text-muted); + margin-bottom: 0.7rem; +} +.guide-toc ul { list-style: none; padding: 0; } +.guide-toc li { + margin: 0; + font-size: 0.83rem; + line-height: 1.5; +} +.guide-toc a { + display: block; + padding: 0.3rem 0; + color: var(--text-muted); + border-left: 2px solid transparent; + margin-left: -1px; + padding-left: 0.6rem; + transition: color var(--transition), border-color var(--transition); +} +.guide-toc a:hover { color: var(--text); } +.guide-toc a.active { + color: var(--ember-bright); + border-left-color: var(--ember); +} +.guide-toc li.h3 a { padding-left: 1.4rem; font-size: 0.79rem; } + +/* ── Footer link in content ─────────────────────────────── */ +.guide-edit { + display: inline-flex; + align-items: center; + gap: 0.4rem; + margin-top: 2rem; + padding: 0.5rem 0.85rem; + font-size: 0.84rem; + color: var(--text-muted); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + transition: all var(--transition); +} +.guide-edit:hover { + color: var(--ember-bright); + border-color: var(--ember); +} +.guide-edit svg { width: 14px; height: 14px; } + +/* ── Search overlay (Cmd+K) ─────────────────────────────── */ +.guide-search-overlay { + display: none; + position: fixed; + inset: 0; + background: rgba(0,0,0,.5); + backdrop-filter: blur(6px); + -webkit-backdrop-filter: blur(6px); + z-index: 300; + align-items: flex-start; + justify-content: center; + padding-top: 12vh; +} +.guide-search-overlay.open { display: flex; } +.guide-search-modal { + width: min(620px, 92vw); + background: var(--bg-card); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + box-shadow: var(--shadow-lg); + overflow: hidden; + max-height: 70vh; + display: flex; + flex-direction: column; +} +.guide-search-input { + width: 100%; + background: transparent; + border: none; + border-bottom: 1px solid var(--border); + color: var(--text); + font: 500 1rem var(--font-sans); + padding: 1rem 1.1rem 1rem 2.6rem; + outline: none; + background-image: + url("data:image/svg+xml;utf8,"); + background-repeat: no-repeat; + background-position: 1rem center; +} +.guide-search-input::placeholder { color: var(--text-muted); } +.guide-search-results { + list-style: none; + padding: 0.4rem 0; + margin: 0; + overflow-y: auto; + flex: 1; +} +.guide-search-results li { margin: 0; } +.guide-search-results a { + display: block; + padding: 0.65rem 1rem; + color: var(--text); + text-decoration: none; + border-left: 3px solid transparent; + transition: all 0.12s ease; +} +.guide-search-results a:hover, +.guide-search-results a.focused { + background: var(--bg-elev); + border-left-color: var(--ember); +} +.guide-search-results .section { + font-size: 0.74rem; + text-transform: uppercase; + color: var(--text-muted); + letter-spacing: 0.08em; +} +.guide-search-results .title { + font-size: 0.95rem; + font-weight: 500; + margin-top: 2px; +} +.guide-search-results mark { + background: rgba(249,115,22,.25); + color: var(--text); + padding: 0 1px; + border-radius: 2px; +} +.guide-search-empty { + padding: 2rem 1rem; + text-align: center; + color: var(--text-muted); + font-size: 0.9rem; +} +.guide-search-footer { + padding: 0.55rem 1rem; + font-size: 0.74rem; + color: var(--text-muted); + border-top: 1px solid var(--border); + display: flex; + gap: 1rem; + justify-content: flex-end; +} +.guide-search-footer kbd { + font-family: var(--font-mono); + background: var(--bg-elev); + border: 1px solid var(--border-strong); + border-radius: 3px; + padding: 1px 5px; + font-size: 0.7rem; + color: var(--text-secondary); +} + +/* ── Mobile drawer for sidebar ─────────────────────────── */ +.guide-mobile-bar { + display: none; + position: sticky; + top: 64px; + z-index: 90; + background: color-mix(in srgb, var(--bg) 85%, transparent); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + border-bottom: 1px solid var(--border); + padding: 0.6rem 1rem; + align-items: center; + gap: 0.6rem; +} +.guide-mobile-bar button { + background: var(--bg-elev); + border: 1px solid var(--border); + color: var(--text); + padding: 0.3rem 0.65rem; + border-radius: var(--radius-sm); + font-size: 0.8rem; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 0.35rem; +} +.guide-mobile-bar svg { width: 14px; height: 14px; } +.guide-mobile-bar .crumb { + font-size: 0.85rem; + color: var(--text-secondary); + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +@media (max-width: 880px) { + .guide-mobile-bar { display: flex; } + .guide-sidebar.open { + position: fixed; + top: 64px; + left: 0; + right: 0; + bottom: 0; + z-index: 95; + background: var(--bg); + padding: 1.2rem 1rem 2rem; + overflow-y: auto; + max-height: none; + } +} + +/* ── Light theme adjustments ─────────────────────────────── */ +[data-theme="light"] .guide-content table { background: #fff; } +[data-theme="light"] .guide-content thead { background: #f7f8fb; } +[data-theme="light"] .guide-content tbody tr:hover { background: #fafbfd; } +[data-theme="light"] .guide-content .mermaid { background: #fafbfd; } diff --git a/site/features.html b/site/features.html index 6538958c..3e391382 100644 --- a/site/features.html +++ b/site/features.html @@ -3,14 +3,12 @@ - Features — ForgeLM - Features — ForgeLM + - - + + @@ -21,6 +19,7 @@ + @@ -31,17 +30,32 @@ ForgeLM - + + @@ -51,18 +65,9 @@ @@ -74,8 +79,8 @@

-

Training & alignmentEğitim ve alignment

-

Six post-training paradigms, parameter-efficient methods, and distributed configs.Altı post-training paradigması, parametre-verimli yöntemler ve dağıtık konfigürasyonlar.

+

Training & alignment

+

Six post-training paradigms, parameter-efficient methods, and distributed configs.

@@ -83,47 +88,47 @@

Training & alignment

SFT

-

Supervised fine-tuning on instruction-formatted JSONL. Multi-dataset mixing with configurable ratios.Talimat formatlı JSONL üzerinde denetimli fine-tuning. Konfigüre edilebilir oranlarla çoklu veri seti karışımı.

+

Supervised fine-tuning on instruction-formatted JSONL.

-

DPO & SimPO

-

Direct Preference Optimization on chosen/rejected pairs; SimPO for reference-free, lower-memory variants.Tercih edilen / reddedilen çiftler üzerinde DPO; referans modelsiz, düşük bellekli varyantlar için SimPO.

+

DPO & SimPO

+

Direct Preference Optimization on chosen/rejected pairs.

KTO

-

Kahneman-Tversky preference learning on binary feedback. Works when you only have thumbs-up / thumbs-down signals.İkili geri bildirimde Kahneman-Tversky tercih öğrenmesi. Sadece thumbs-up / thumbs-down sinyaliniz varsa çalışır.

+

Kahneman-Tversky preference learning on binary feedback.

ORPO

-

Single-pass odds-ratio preference optimization. Combines SFT + DPO into one stage; faster wall-clock.Tek geçişli odds-ratio tercih optimizasyonu. SFT + DPO'yu tek aşamaya birleştirir; daha hızlı wall-clock.

+

Single-pass odds-ratio preference optimization.

GRPO

-

Group Relative Policy Optimization for reasoning RL. Built-in format/length shaping reward, or your own reward function.Akıl yürütme RL için grup-göreli politika optimizasyonu. Yerleşik format/uzunluk reward'ı veya kendi reward fonksiyonunuz.

+

Group Relative Policy Optimization for reasoning RL.

QLoRA + DoRA

-

4-bit NF4 quantization with LoRA. PiSSA, rsLoRA, DoRA variants. Train 7B-13B models on a single 12 GB GPU.LoRA ile 4-bit NF4 kuantizasyon. PiSSA, rsLoRA, DoRA varyantları. Tek 12 GB GPU'da 7B-13B model eğitin.

+

4-bit NF4 quantization with LoRA.

GaLore

-

Gradient low-rank projection for full-parameter training without LoRA. Memory at LoRA levels, capacity of full fine-tune.LoRA olmadan full-parameter eğitim için gradient low-rank projeksiyonu. LoRA seviyesinde bellek, full fine-tune kapasitesi.

+

Gradient low-rank projection for full-parameter training.

-

DeepSpeed & FSDP

-

Multi-GPU distributed training. ZeRO-2 / ZeRO-3 presets, FSDP, Unsloth backend (2-5× faster).Çoklu-GPU dağıtık eğitim. ZeRO-2 / ZeRO-3 hazır ayarlar, FSDP, Unsloth backend (2-5× hızlı).

+

DeepSpeed & FSDP

+

Multi-GPU distributed training. ZeRO presets, FSDP, Unsloth backend.

-

Long-context

-

RoPE scaling, NEFTune noise injection, sliding-window attention, sample packing — train on 32K-128K context.RoPE scaling, NEFTune noise injection, kayar-pencere attention, sample packing — 32K-128K context'te eğitim.

+

Long-context

+

RoPE scaling, NEFTune noise injection, sample packing.

@@ -137,41 +142,41 @@

Long-context

-

Evaluation & safetyDeğerlendirme ve güvenlik

-

Benchmarks, judges, harm classification, and the auto-revert that ties them together.Benchmark'lar, judge'lar, zarar sınıflandırması ve hepsini bağlayan otomatik geri alma.

+

Evaluation & safety

+

Benchmarks, judges, harm classification, and the auto-revert that ties them together.

-

Benchmark integrationBenchmark entegrasyonu

-

Plug-in lm-evaluation-harness tasks. Per-task floor thresholds; auto-revert if any drops below the floor.lm-evaluation-harness görev entegrasyonu. Görev başı taban eşikleri; biri tabanın altına düşerse otomatik geri alma.

+

Benchmark integration

+

Plug-in lm-evaluation-harness tasks. Per-task floor thresholds.

-

LLM-as-judgeLLM-as-judge

-

Quality scoring via OpenAI API or a local judge model. Pairwise comparison, single-rubric scoring, ELO-style ranking.OpenAI API veya yerel judge modeliyle kalite skorlaması. İkili karşılaştırma, tek-rubrik skorlaması, ELO sıralaması.

+

LLM-as-judge

+

Quality scoring via OpenAI API or a local judge model.

-

Llama Guard safetyLlama Guard güvenliği

-

Confidence-weighted scoring across 14 harm categories (S1-S14). Severity tiers, cross-run trend tracking.14 zarar kategorisinde (S1-S14) güven-ağırlıklı skorlama. Ciddiyet katmanları, koşular arası trend izleme.

+

Llama Guard safety

+

Confidence-weighted scoring across 14 harm categories.

-

Auto-revertOtomatik geri alma

-

If loss, benchmark, or safety thresholds fail, ForgeLM rolls back to the last-good checkpoint and emits a structured incident record.Loss, benchmark veya güvenlik eşikleri başarısız olursa ForgeLM son-iyi checkpoint'e döner ve yapılandırılmış olay kaydı üretir.

+

Auto-revert

+

If thresholds fail, ForgeLM rolls back to the last-good checkpoint.

-

Trend trackingTrend izleme

-

Cross-run safety / quality history. See if a category quietly drifts before it crosses the threshold.Koşular arası güvenlik / kalite geçmişi. Bir kategori eşiği aşmadan önce sessizce kayıyor mu görün.

+

Trend tracking

+

Cross-run safety / quality history.

-

Exit codesExit kodları

-

0 / 1 / 2 / 3 / 4 — a public contract for CI/CD. Fail-loud is the default; no silent || true.0 / 1 / 2 / 3 / 4 — CI/CD için kamuya açık kontrat. Sessiz başarısızlık yok; || true yasak.

+

Exit codes

+

0 / 1 / 2 / 3 / 4 — a public contract for CI/CD.

@@ -185,51 +190,51 @@

Exit codes
-

Data ingestion & auditVeri ingest'i ve denetimi

-

Raw documents to clean JSONL, with PII / secrets / quality / leakage all surfaced before training.Ham dokümandan temiz JSONL'a — eğitimden önce tüm PII / sırlar / kalite / sızıntı yüzeyde.

+

Data ingestion & audit

+

Raw documents to clean JSONL, with PII / secrets / quality / leakage all surfaced before training.

-

Multi-format ingestÇoklu format ingest'i

-

PDF, DOCX, EPUB, TXT, Markdown → SFT-ready JSONL. Markdown-aware splitter; DOCX tables emit as Markdown tables; PDF header/footer dedup.PDF, DOCX, EPUB, TXT, Markdown → SFT-hazır JSONL. Markdown-bilen splitter; DOCX tabloları Markdown tablo olarak; PDF header/footer dedup.

+

Multi-format ingest

+

PDF, DOCX, EPUB, TXT, Markdown → SFT-ready JSONL.

-

PII maskingPII maskeleme

-

Email, phone, credit card (Luhn-validated), IBAN, national IDs (TR / DE / FR / US-SSN). Masks at ingest time, before chunks land in JSONL.E-posta, telefon, kredi kartı (Luhn doğrulamalı), IBAN, ulusal kimlik (TR / DE / FR / US-SSN). Chunk'lar JSONL'a düşmeden ingest sırasında maskelenir.

+

PII masking

+

Email, phone, credit card, IBAN, national IDs.

-

Secrets scrubbingSırların temizlenmesi

-

AWS keys, GitHub PATs, Slack / OpenAI / Google tokens, JWTs, full PEM private-key blocks (BEGIN…END), Azure storage strings — redacted with [REDACTED-SECRET].AWS anahtarları, GitHub PAT'leri, Slack / OpenAI / Google token'ları, JWT'ler, tam PEM özel anahtar blokları (BEGIN…END), Azure storage string'leri — [REDACTED-SECRET] ile maskelenir.

+

Secrets scrubbing

+

AWS keys, GitHub PATs, JWTs — redacted with [REDACTED-SECRET].

-

Near-duplicate detectionNear-duplicate tespiti

-

LSH-banded simhash (default, exact recall) or MinHash LSH for >50K-row corpora. O(n × k) typical, streaming, CPU-only.LSH-banded simhash (varsayılan, kesin recall) veya 50K+ satır corpus için MinHash LSH. Tipik O(n × k), streaming, CPU.

+

Near-duplicate detection

+

LSH-banded simhash or MinHash LSH.

-

Quality filterKalite filtresi

-

Gopher / C4 / RefinedWeb-style heuristics: low-alpha, abnormal word length, repeated lines, short paragraphs. Conservative — never silently drops.Gopher / C4 / RefinedWeb tarzı heuristik: düşük alfa, anormal kelime uzunluğu, tekrarlayan satırlar, kısa paragraflar. Muhafazakar — sessizce satır düşürmez.

+

Quality filter

+

Gopher / C4 / RefinedWeb-style heuristics.

-

Language detectionDil tespiti

-

Top-3 language counts per split via langdetect. Useful when your dataset is supposed to be Turkish but 12% slipped in as English.langdetect ile split başına top-3 dil sayısı. Veri setiniz Türkçe olmalıyken %12'si İngilizce kaymışsa fark eder.

+

Language detection

+

Top-3 language counts per split via langdetect.

-

Cross-split leakageSplit-arası sızıntı

-

Catches the most expensive evaluation bug: train rows that also appear in validation/test. Audit refuses to certify a leaky split.En pahalı değerlendirme hatasını yakalar: validation/test'te de görünen train satırları. Audit sızdıran split'i onaylamaz.

+

Cross-split leakage

+

Catches train rows that also appear in validation/test.

-

Annex IV provenanceAnnex IV provenance

-

Audit report is automatically embedded in the EU AI Act Article 10 governance artifact when present at training time.Eğitim sırasında mevcutsa audit raporu EU AI Act Article 10 governance artifact'ına otomatik gömülür.

+

Annex IV provenance

+

Audit report embedded in EU AI Act Article 10 governance artifact.

@@ -243,56 +248,56 @@

Annex IV provenance
-

Enterprise & MLOpsKurumsal ve MLOps

-

Built for pipelines: containers, webhooks, structured outputs, air-gap, model cards.Hatlar için yapıldı: konteynerler, webhook'lar, yapılandırılmış çıktı, air-gap, model card.

+

Enterprise & MLOps

+

Built for pipelines: containers, webhooks, structured outputs, air-gap, model cards.

-

Webhook notificationsWebhook bildirimleri

-

Slack and Teams alerts on training start, success, failure, auto-revert. Structured payloads — pipe to your incident tool.Eğitim başlangıcında, başarıda, hatada, otomatik geri almada Slack ve Teams alert'leri. Yapılandırılmış payload — incident aracınıza bağlayın.

+

Webhook notifications

+

Slack and Teams alerts on training events.

-

Experiment trackingDeney takibi

-

W&B, MLflow, TensorBoard via report_to. Pluggable, not hardcoded. Use what your team already uses.report_to üzerinden W&B, MLflow, TensorBoard. Pluggable, hardcoded değil. Ekibinizin zaten kullandığını kullanın.

+

Experiment tracking

+

W&B, MLflow, TensorBoard via report_to.

-

JSON output modeJSON çıktı modu

-

--output-format json emits a machine-readable envelope — perfect for piping to jq, GitHub Actions, or your custom dashboard.--output-format json makine-okunur bir zarf üretir — jq'a, GitHub Actions'a veya özel dashboard'unuza pipe için ideal.

+

JSON output mode

+

--output-format json emits a machine-readable envelope.

-

Air-gap operationAir-gap operasyonu

-

No mandatory internet calls. Pre-cache models / datasets / tokenizers; run training in an isolated network with full feature parity.Zorunlu internet çağrısı yok. Model / veri seti / tokenizer'ı önceden cache'leyin; izole ağda tam özellik paritesiyle koşun.

+

Air-gap operation

+

No mandatory internet calls.

-

Docker & composeDocker ve compose

-

Official Dockerfile and docker-compose.yml. Reproducible runs across local, on-prem, and cloud — same image, same behaviour.Resmi Dockerfile ve docker-compose.yml. Yerel, on-prem ve cloud arasında yeniden üretilebilir koşular — aynı imaj, aynı davranış.

+

Docker & compose

+

Official Dockerfile and docker-compose.yml.

-

Model card auto-genOtomatik Model Card

-

HuggingFace-compatible README with metrics, benchmarks, training config snapshot. Drop-in for HF Hub publish.Metrikleri, benchmark'ları ve training config snapshot'ını içeren HuggingFace uyumlu README. HF Hub yayını için drop-in.

+

Model card auto-gen

+

HuggingFace-compatible README with metrics and config.

-

GPU cost estimationGPU maliyet tahmini

-

Auto-detection across 18 GPU profiles (A100 / H100 / RTX 4090 / L40S / etc.) with per-run cost tracking against your hourly rate.18 GPU profili (A100 / H100 / RTX 4090 / L40S / vb.) otomatik algılama, saatlik tarifenize göre koşu başı maliyet izleme.

+

GPU cost estimation

+

Auto-detection across 18 GPU profiles with cost tracking.

-

Synthetic data pipelineSentetik veri hattı

-

Teacher-to-student distillation with --generate-data. Augment your dataset; cite the teacher in the model card automatically.--generate-data ile öğretmenden öğrenciye damıtma. Veri setinizi büyütün; öğretmen otomatik olarak model card'a referans olur.

+

Synthetic data pipeline

+

Teacher-to-student distillation with --generate-data.

-

Model mergingModel birleştirme

-

TIES, DARE, SLERP, linear merge of multiple adapters via --merge. Compose specialists into a generalist.--merge ile birden çok adapter için TIES, DARE, SLERP, lineer birleştirme. Uzmanları genel bir modelde birleştirin.

+

Model merging

+

TIES, DARE, SLERP, linear merge via --merge.

@@ -301,16 +306,10 @@

Model merging
-

- Want to see it in YAML? - YAML olarak görmek ister misiniz? -

-

- Every feature on this page maps to a field on a single YAML config. Walk through it in the quickstart. - Bu sayfadaki her özellik tek bir YAML config'te bir alana eşlenir. Quickstart'ta adım adım gezin. -

+

Want to see it in YAML?

+

Every feature on this page maps to a field on a single YAML config.

@@ -322,10 +321,10 @@

diff --git a/site/guide.html b/site/guide.html new file mode 100644 index 00000000..e54a93b5 --- /dev/null +++ b/site/guide.html @@ -0,0 +1,144 @@ + + + + + + User Guide — ForgeLM + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ + +
+ + + + + +
+ + + + +
+ + + + + + + + + + + diff --git a/site/index.html b/site/index.html index ee9ecb98..062f2836 100644 --- a/site/index.html +++ b/site/index.html @@ -3,15 +3,12 @@ - ForgeLM — Config-driven LLM fine-tuning toolkit - + ForgeLM — Config-driven LLM fine-tuning toolkit + - - + + @@ -22,6 +19,7 @@ + @@ -39,25 +37,36 @@ ForgeLM - + @@ -75,46 +84,33 @@
- Open source · Apache 2.0 · v0.5.2 - Açık kaynak · Apache 2.0 · v0.5.2 + Open source · Apache 2.0 · v0.5.2 -

- YAML in.
Fine-tuned model out.
- YAML gir.
Fine-tuned model al.
-

+

YAML in.
Fine-tuned model out.

-

- ForgeLM is the config-driven LLM fine-tuning toolkit for teams that ship into regulated environments. The full alignment stack — SFT, DPO, SimPO, KTO, ORPO, GRPO — with integrated safety evaluation, EU AI Act audit trails, and auto-revert on quality regression. - ForgeLM, regülasyonlu ortamlara üretim çıkaran ekipler için konfigürasyon odaklı LLM fine-tuning araç setidir. Tam alignment yığını — SFT, DPO, SimPO, KTO, ORPO, GRPO — entegre güvenlik değerlendirmesi, EU AI Act denetim kayıtları ve kalite regresyonunda otomatik geri alma ile. -

+

ForgeLM is the config-driven LLM fine-tuning toolkit for teams that ship into regulated environments.

- EU AI Act ready - EU AI Act uyumlu + EU AI Act ready - CPU-friendly audit - CPU dostu denetim + CPU-friendly audit - Air-gap capable - Air-gap hazır + Air-gap capable - CI/CD-native - CI/CD-yerli + CI/CD integrated
@@ -151,31 +147,19 @@

6
-
- Trainer types - Trainer türü -
+
Trainer types
18
-
- GPU profiles auto-detected - Otomatik algılanan GPU profili -
+
GPU profiles auto-detected
5
-
- Ingest formats - Ingest formatı -
+
Ingest formats
100%
-
- Config-driven, declarative - Konfigürasyon odaklı, deklaratif -
+
Config-driven, declarative
@@ -185,68 +169,41 @@

- - The complete alignment stack - Eksiksiz alignment yığını - -

- From base model to production-ready - Temel modelden üretime hazır modele -

-

- Six post-training paradigms behind one declarative interface. Pick what your task needs; ForgeLM handles the wiring. - Altı post-training paradigması tek bir deklaratif arayüzün arkasında. Görevinizin ihtiyacını seçin; bağlantıyı ForgeLM kurar. -

+ The complete alignment stack +

From base model to production-ready

+

Six post-training paradigms behind one declarative interface.

01

SFT

-

- Supervised fine-tuning on instruction pairs - Talimat çifti üzerinde denetimli fine-tuning -

+

Supervised fine-tuning on instruction pairs

02

DPO

-

- Direct Preference Optimization on chosen/rejected pairs - Tercih edilen / reddedilen çiftler üzerinde direkt tercih optimizasyonu -

+

Direct Preference Optimization on chosen/rejected pairs

03

SimPO

-

- Reference-free preference learning, lower memory - Referans modelsiz tercih öğrenmesi, düşük bellek -

+

Reference-free preference learning, lower memory

04

KTO

-

- Kahneman-Tversky on binary feedback signals - İkili geri bildirim sinyallerinde Kahneman-Tversky -

+

Kahneman-Tversky on binary feedback signals

05

ORPO

-

- Odds Ratio Preference Optimization, single pass - Odds-Ratio tercih optimizasyonu, tek geçişli -

+

Odds Ratio Preference Optimization, single pass

06

GRPO

-

- Group Relative Policy Optimization for reasoning RL - Akıl yürütme RL için grup-göreli politika optimizasyonu -

+

Group Relative Policy Optimization for reasoning RL

@@ -256,18 +213,9 @@

GRPO

- - Why ForgeLM - Neden ForgeLM - -

- Built for the path to production - Üretime giden yol için tasarlandı -

-

- Three things separate ForgeLM from notebook-first frameworks. - ForgeLM'i notebook merkezli framework'lerden ayıran üç şey. -

+ Why ForgeLM +

Built for the path to production

+

Three things separate ForgeLM from notebook-first frameworks.

@@ -275,14 +223,8 @@

-

- Declarative, not imperative - Deklaratif, imperatif değil -

-

- Your run is a YAML file under version control. Pydantic validates every field. --dry-run proves the config will load before you spend GPU hours. - Koşunuz versiyon kontrollü bir YAML dosyası. Pydantic her alanı doğrular. --dry-run GPU saatleri harcamadan konfigürasyonun yükleneceğini kanıtlar. -

+

Declarative, not imperative

+

Your run is a YAML file under version control.

YAML Pydantic @@ -294,14 +236,8 @@

-

- Compliance is shipped, not promised - Uyumluluk vaadi değil ürün -

-

- Every run emits an Annex IV artifact tracing data → training → evaluation → safety. Article 9 risk assessment, Article 10 data governance, Article 12 record-keeping — wired in. - Her koşu, veri → eğitim → değerlendirme → güvenlik izini çıkaran bir Annex IV artifact'ı üretir. Article 9 risk değerlendirmesi, Article 10 veri yönetimi, Article 12 kayıt tutma — bağlandı. -

+

Compliance is shipped, not promised

+

Every run emits an Annex IV artifact.

Annex IV Article 9-17 @@ -313,14 +249,8 @@

-

- Auto-revert on regression - Regresyonda otomatik geri alma -

-

- When a benchmark drops below the floor or Llama Guard flags a critical category, ForgeLM rolls back to the last-good checkpoint and emits a structured incident record. CI/CD-native exit codes (0/1/2/3/4) for pipeline gating. - Bir benchmark tabanın altına düşerse veya Llama Guard kritik bir kategoriyi flagleyince ForgeLM son-iyi checkpoint'e döner ve yapılandırılmış bir olay kaydı üretir. Pipeline kapısı için CI/CD-yerli exit kodları (0/1/2/3/4). -

+

Auto-revert on regression

+

When a benchmark drops below the floor, ForgeLM rolls back.

Llama Guard exit codes @@ -335,33 +265,16 @@

- - Capabilities - Yetenekler - -

- Everything the modern post-training stack needs - Modern post-training yığınının ihtiyacı olan her şey -

-

- From data ingestion through evaluation to deployment artifacts — without notebook ceremony. - Veri ingest'inden değerlendirmeye, deployment artifact'larına kadar — notebook seremonisi olmadan. -

+ Capabilities +

Everything the modern post-training stack needs

+

From data ingestion through evaluation to deployment artifacts.

-
- -
-

- Document ingestion - Doküman ingest'i -

-

- PDF, DOCX, EPUB, TXT, Markdown → SFT-ready JSONL. Markdown-aware splitter, DOCX table preservation, PDF header/footer dedup. - PDF, DOCX, EPUB, TXT, Markdown → SFT-hazır JSONL. Markdown-bilen splitter, DOCX tablo koruması, PDF header/footer dedup. -

+
+

Document ingestion

+

PDF, DOCX, EPUB, TXT, Markdown → SFT-ready JSONL.

forgelm ingest --strategy markdown @@ -369,17 +282,9 @@

-
- -
-

- Dataset audit - Veri seti denetimi -

-

- PII / secrets / cross-split leakage / language detect / near-duplicate (simhash + MinHash LSH) / quality filter — all CPU-only and streaming. - PII / sırlar / split-arası sızıntı / dil tespiti / near-duplicate (simhash + MinHash LSH) / kalite filtresi — tamamen CPU tabanlı ve akış halinde. -

+
+

Dataset audit

+

PII, secrets, leakage, language detect, near-duplicates.

forgelm audit streaming @@ -387,17 +292,9 @@

-
- -
-

- QLoRA + DoRA + GaLore - QLoRA + DoRA + GaLore -

-

- 4-bit NF4 quantization with PEFT adapters. PiSSA / rsLoRA / DoRA variants. GaLore for full-parameter on a single GPU. - PEFT adapter'larıyla 4-bit NF4 kuantizasyon. PiSSA / rsLoRA / DoRA varyantları. Tek GPU'da full-parameter için GaLore. -

+
+

QLoRA + DoRA + GaLore

+

4-bit NF4 quantization with PEFT adapters.

QLoRA DoRA @@ -406,17 +303,9 @@

-
- -
-

- Safety evaluation - Güvenlik değerlendirmesi -

-

- Llama Guard with confidence-weighted scoring across S1–S14 harm categories, severity tiers, cross-run trend tracking, and auto-revert on regression. - S1–S14 zarar kategorilerinde güven-ağırlıklı skorlama, ciddiyet katmanları, koşular arası trend izleme ve regresyonda otomatik geri alma. -

+
+

Safety evaluation

+

Llama Guard with confidence-weighted scoring.

Llama Guard S1-S14 @@ -424,17 +313,9 @@

-
- -
-

- Benchmarking - Benchmark -

-

- Plug-in lm-evaluation-harness tasks. LLM-as-judge with OpenAI or local model. Floors per task; auto-revert if any drops. - lm-evaluation-harness entegrasyonu. OpenAI veya yerel modelle LLM-as-judge. Görev bazlı tabanlar; biri düşerse otomatik geri alma. -

+
+

Benchmarking

+

Plug-in lm-evaluation-harness tasks.

lm-eval-harness judge @@ -442,17 +323,9 @@

-
- -
-

- Distributed training - Dağıtık eğitim -

-

- DeepSpeed ZeRO-2 / ZeRO-3 presets, FSDP, multi-GPU configs. MoE support (Qwen3, Mixtral, DeepSeek). - DeepSpeed ZeRO-2 / ZeRO-3 hazır ayarlar, FSDP, çoklu-GPU konfigürasyonu. MoE desteği (Qwen3, Mixtral, DeepSeek). -

+
+

Distributed training

+

DeepSpeed ZeRO presets, FSDP, multi-GPU configs.

DeepSpeed FSDP @@ -461,51 +334,27 @@

-
- -
-

- VRAM fit-check - VRAM fit-check -

-

- Pre-flight memory estimator. FITS / TIGHT / OOM / UNKNOWN verdict with concrete recommendations before you submit a long job. - Uçuş öncesi bellek tahmincisi. Uzun işi göndermeden önce FITS / TIGHT / OOM / UNKNOWN verdict'i ve somut öneriler. -

+
+

VRAM fit-check

+

Pre-flight memory estimator.

--fit-check
-
- -
-

- Interactive chat - İnteraktif sohbet -

-

- Streaming REPL with /reset, /save, /temperature, /system commands and optional safety routing. - /reset, /save, /temperature, /system komutları ve opsiyonel güvenlik routing'i ile akışlı REPL. -

+
+

Interactive chat

+

Streaming REPL with safety routing.

forgelm chat
-
- -
-

- Export & deploy - Export ve deploy -

-

- GGUF export with 6 quant levels and SHA-256 manifest. Generate Ollama / vLLM / TGI / HF-Endpoints deployment configs in one command. - 6 kuantizasyon seviyesi ve SHA-256 manifest ile GGUF export. Tek komutta Ollama / vLLM / TGI / HF-Endpoints deployment config üret. -

+
+

Export & deploy

+

GGUF export with 6 quant levels.

GGUF deploy @@ -515,8 +364,7 @@

@@ -527,25 +375,16 @@

- - A real config — not a screenshot - Gerçek bir konfigürasyon — ekran görüntüsü değil - -

- One YAML, end-to-end run - Bir YAML, uçtan uca koşu -

-

- A SFT → DPO run with safety eval, benchmark gate, and Annex IV export. Copy this, change the names, and you have a reproducible training pipeline. - Güvenlik değerlendirmesi, benchmark kapısı ve Annex IV export ile bir SFT → DPO koşusu. Bunu kopyalayın, isimleri değiştirin — yeniden üretilebilir bir eğitim hattınız hazır. -

+ A real config — not a screenshot +

One YAML, end-to-end run

+

A SFT → DPO run with safety eval, benchmark gate, and Annex IV export.

configs/policy-bot.yaml - +
model:
   name_or_path: "Qwen/Qwen2.5-7B-Instruct"
@@ -591,7 +430,7 @@ 

terminal - +
$ forgelm --config configs/policy-bot.yaml --dry-run   # validate
 $ forgelm --config configs/policy-bot.yaml --fit-check  # VRAM check
@@ -606,14 +445,8 @@ 

- - Built for these workflows - Bu iş akışları için tasarlandı - -

- Use cases that actually ship - Gerçekten üretime çıkan kullanım senaryoları -

+ Built for these workflows +

Use cases that actually ship

@@ -622,14 +455,8 @@

-

- Domain expert from policy PDFs - Politika PDF'lerinden alan uzmanı -

-

- Drop your regulatory corpus into forgelm ingest, audit it, and SFT a model that answers in your domain's voice — with PII redacted at ingest, before training. - Regülasyon korpusunuzu forgelm ingest'e bırakın, denetleyin ve alanınızın diliyle cevap veren bir modeli SFT'leyin — PII ingest sırasında, eğitimden önce maskelenir. -

+

Domain expert from policy PDFs

+

Drop your regulatory corpus into forgelm ingest.

forgelm quickstart byod
@@ -639,14 +466,8 @@

-

- Customer support assistant - Müşteri destek asistanı -

-

- SFT on past tickets, DPO on agent thumbs-up/down feedback, Llama Guard safety routing, auto-revert if helpfulness drops. Ship to vLLM with one command. - Geçmiş ticket'larda SFT, agent thumbs-up/down geri bildirimde DPO, Llama Guard güvenlik routing'i, yardımseverlik düşerse otomatik geri alma. Tek komutla vLLM'e gönderim. -

+

Customer support assistant

+

SFT on past tickets, DPO on agent feedback.

forgelm quickstart customer-support

@@ -656,14 +477,8 @@

-

- Code copilot fine-tune - Kod copilot fine-tune -

-

- Multi-dataset mix (your repo + open code), SFT + ORPO, GGUF export at q4_k_m for local inference. Synthetic data pipeline distils a teacher into your student. - Çoklu veri seti karışımı (kendi repo'nuz + açık kod), SFT + ORPO, yerel inference için q4_k_m'de GGUF export. Sentetik veri hattı bir öğretmeni öğrencinize damıtır. -

+

Code copilot fine-tune

+

Multi-dataset mix, SFT + ORPO, GGUF export.

forgelm quickstart code-assistant
@@ -673,14 +488,8 @@

-

- Reasoning RL with GRPO - GRPO ile akıl yürütme RL -

-

- Built-in format/length shaping rewards or your own reward function. Group-relative policy optimization without writing a single training-loop line. - Yerleşik format/uzunluk ödülleri veya kendi reward fonksiyonunuz. Tek bir training loop satırı yazmadan grup-göreli politika optimizasyonu. -

+

Reasoning RL with GRPO

+

Built-in shaping rewards or your own reward function.

forgelm quickstart math-reasoning
@@ -692,23 +501,11 @@

-

- Ship your next fine-tune in an afternoon. - Bir sonraki fine-tune'u bir öğleden sonrasında gönderin. -

-

- Pick a template, point it at your data, watch the audit report go green, and let ForgeLM forge the rest. - Bir şablon seçin, verilerinize yönlendirin, denetim raporu yeşile dönsün — kalanını ForgeLM dövsün. -

+

Ship your next fine-tune in an afternoon.

+

Pick a template, point it at your data, watch the audit report go green.

@@ -727,38 +524,35 @@

ForgeLM

- +

@@ -766,10 +560,7 @@

Legal © 2026 ForgeLM - - Built for teams that ship into regulated environments. - Regülasyonlu ortamlara üretim çıkaran ekipler için yapıldı. - + Built for teams that ship into regulated environments.

diff --git a/site/js/guide.js b/site/js/guide.js new file mode 100644 index 00000000..871c59e1 --- /dev/null +++ b/site/js/guide.js @@ -0,0 +1,628 @@ +/** + * ForgeLM site — user guide router & renderer. + * + * Reads the navigation tree from window.ForgeLMUserManualsIndex and the + * per-language page content from window.ForgeLMUserManuals[], then + * drives a single guide.html shell: + * + * - sidebar (sections + pages) + * - hash-based routing (#/
/) + * - on-this-page TOC (h2/h3 anchors with scrollspy) + * - reading progress bar + * - Cmd/Ctrl+K search overlay + * - prev / next pager + * - mermaid diagram initialisation + * - lazy loading of additional language data files + * + * Reacts to language changes by listening for the `lang` attribute on + * (set by js/i18n.js). + */ +(function () { + 'use strict'; + + var GUIDE_BASE = 'guide.html'; + var GH_EDIT_BASE = 'https://github.com/cemililik/ForgeLM/edit/main/docs/usermanuals'; + var DEFAULT_ROUTE = 'getting-started/introduction'; + + var state = { + lang: 'en', + route: null, + loadedLangs: { en: true }, // populated as we lazy-load others + searchOpen: false, + }; + + document.addEventListener('DOMContentLoaded', function () { + if (!document.querySelector('.guide-layout')) return; + + state.lang = document.documentElement.lang || 'en'; + + buildSidebar(); + initSearch(); + initProgressBar(); + initMobileDrawer(); + initLanguageWatcher(); + initMermaid(); + + var initial = parseHash(window.location.hash) || DEFAULT_ROUTE; + navigate(initial, /*replace*/ true); + + window.addEventListener('hashchange', function () { + var route = parseHash(window.location.hash); + if (route) navigate(route, /*replace*/ true); + }); + }); + + /* ──────────────────────────────────────────── routing */ + + function parseHash(hash) { + if (!hash) return null; + var stripped = hash.replace(/^#\/?/, ''); + if (!stripped) return null; + if (stripped.indexOf('/') === -1) return null; + return stripped; + } + + function navigate(route, replace) { + state.route = route; + var newHash = '#/' + route; + if (window.location.hash !== newHash) { + if (replace) { + history.replaceState(null, '', newHash); + } else { + history.pushState(null, '', newHash); + } + } + renderCurrentRoute(); + closeSearch(); + closeSidebar(); + window.scrollTo(0, 0); + } + + /* ──────────────────────────────────────────── sidebar */ + + function buildSidebar() { + var nav = document.getElementById('guide-nav'); + if (!nav) return; + var idx = window.ForgeLMUserManualsIndex; + if (!idx) return; + + var lang = state.lang; + nav.innerHTML = ''; + + idx.sections.forEach(function (section) { + var wrap = document.createElement('div'); + wrap.className = 'guide-nav-section'; + wrap.dataset.sectionId = section.id; + + var h4 = document.createElement('h4'); + h4.textContent = section.titles[lang] || section.titles.en; + wrap.appendChild(h4); + + var ul = document.createElement('ul'); + section.pages.forEach(function (page) { + var li = document.createElement('li'); + var a = document.createElement('a'); + a.href = '#/' + section.id + '/' + page.id; + a.dataset.route = section.id + '/' + page.id; + a.textContent = page.titles[lang] || page.titles.en; + a.addEventListener('click', function (e) { + e.preventDefault(); + navigate(a.dataset.route, false); + }); + li.appendChild(a); + ul.appendChild(li); + }); + wrap.appendChild(ul); + nav.appendChild(wrap); + }); + + refreshSidebarActive(); + refreshSidebarFallbackMarks(); + } + + function refreshSidebarActive() { + document.querySelectorAll('#guide-nav a').forEach(function (a) { + a.classList.toggle('active', a.dataset.route === state.route); + }); + } + + function refreshSidebarFallbackMarks() { + var bag = (window.ForgeLMUserManuals || {})[state.lang] || {}; + document.querySelectorAll('#guide-nav a').forEach(function (a) { + var p = bag[a.dataset.route]; + a.classList.toggle('fallback', !!(p && p.fallback)); + }); + } + + /* ──────────────────────────────────────────── render */ + + function renderCurrentRoute() { + var route = state.route; + if (!route) return; + + ensureLangLoaded(state.lang).then(function () { + var lang = state.lang; + var bag = (window.ForgeLMUserManuals || {})[lang] + || (window.ForgeLMUserManuals || {}).en + || {}; + var page = bag[route]; + + if (!page) { + renderNotFound(route); + return; + } + + renderPage(route, page); + }).catch(function (err) { + console.error('Failed to load language', state.lang, err); + renderNotFound(route); + }); + } + + function renderPage(route, page) { + var parts = route.split('/'); + var sectionId = parts[0]; + var pageId = parts[1]; + var idx = window.ForgeLMUserManualsIndex || { sections: [] }; + var section = idx.sections.find(function (s) { return s.id === sectionId; }); + + var content = document.getElementById('guide-content'); + if (!content) return; + + // Update document title. + document.title = page.title + ' — ForgeLM'; + + // Build breadcrumb. + var crumbHtml = + '' + + '' + + 'Guide' + + ''; + if (section) { + crumbHtml += '' + escapeHtml(section.titles[state.lang] || section.titles.en) + '' + + ''; + } + crumbHtml += '' + escapeHtml(page.title) + ''; + + var fallbackBanner = ''; + if (page.fallback || page.missing) { + fallbackBanner = + '
' + + '' + + 'This page has not been translated yet — showing English.' + + '
'; + } + + var pager = buildPagerHtml(sectionId, pageId); + var editUrl = GH_EDIT_BASE + '/' + state.lang + '/' + route + '.md'; + var editLink = + '' + + '' + + 'Edit this page on GitHub' + + ''; + + var descriptionHtml = page.description + ? '

' + escapeHtml(page.description) + '

' + : ''; + + content.innerHTML = + '' + + fallbackBanner + + '

' + escapeHtml(page.title) + '

' + + descriptionHtml + + '
' + page.html + '
' + + pager + + editLink; + + // Re-translate any chrome that data-i18n updated nodes inside the content. + if (window.ForgeLMi18n && window.ForgeLMi18n.setLanguage) { + window.ForgeLMi18n.setLanguage(state.lang); + } + + refreshSidebarActive(); + refreshSidebarFallbackMarks(); + buildOnPageToc(page.headings || []); + updateMobileCrumb(page.title); + + if (window.mermaid && typeof window.mermaid.run === 'function') { + try { + window.mermaid.run({ querySelector: '.guide-content .mermaid' }); + } catch (e) { /* ignore */ } + } + + // After DOM updates, trigger scrollspy refresh. + setTimeout(observeHeadings, 50); + updateProgressBar(); + } + + function renderNotFound(route) { + var content = document.getElementById('guide-content'); + if (!content) return; + content.innerHTML = + '

Page not found

' + + '

The page ' + escapeHtml(route) + ' doesn\'t exist in this guide.

' + + '

Return to the introduction

'; + } + + function buildPagerHtml(sectionId, pageId) { + var idx = window.ForgeLMUserManualsIndex || { sections: [] }; + var flat = []; + idx.sections.forEach(function (s) { + s.pages.forEach(function (p) { + flat.push({ section: s, page: p }); + }); + }); + var here = flat.findIndex(function (e) { + return e.section.id === sectionId && e.page.id === pageId; + }); + if (here === -1) return ''; + + var prev = here > 0 ? flat[here - 1] : null; + var next = here < flat.length - 1 ? flat[here + 1] : null; + + function card(item, dir) { + if (!item) { + return ''; + } + var href = '#/' + item.section.id + '/' + item.page.id; + var labelKey = dir === 'prev' ? 'guide.prev' : 'guide.next'; + var labelDefault = dir === 'prev' ? 'Previous' : 'Next'; + var title = escapeHtml(item.page.titles[state.lang] || item.page.titles.en); + return '' + + '' + labelDefault + '' + + '' + title + '' + + ''; + } + return ''; + } + + /* ──────────────────────────────────────────── on-page TOC */ + + var observerInst = null; + + function buildOnPageToc(headings) { + var toc = document.getElementById('guide-toc'); + if (!toc) return; + if (!headings || headings.length === 0) { + toc.innerHTML = ''; + toc.style.display = 'none'; + return; + } + toc.style.display = ''; + var inner = + '
On this page
' + + ''; + toc.innerHTML = inner; + + toc.querySelectorAll('a').forEach(function (a) { + a.addEventListener('click', function (e) { + e.preventDefault(); + var target = document.getElementById(a.dataset.id); + if (target) { + target.scrollIntoView({ behavior: 'smooth', block: 'start' }); + history.replaceState(null, '', '#/' + state.route + '#' + a.dataset.id); + } + }); + }); + } + + function observeHeadings() { + if (observerInst) observerInst.disconnect(); + var headings = document.querySelectorAll('.guide-content h2, .guide-content h3'); + if (!headings.length) return; + var tocLinks = {}; + document.querySelectorAll('#guide-toc a').forEach(function (a) { + tocLinks[a.dataset.id] = a; + }); + observerInst = new IntersectionObserver(function (entries) { + entries.forEach(function (entry) { + if (!entry.target.id) return; + var link = tocLinks[entry.target.id]; + if (!link) return; + if (entry.isIntersecting) { + // Mark this link active; clear others in same TOC. + Object.values(tocLinks).forEach(function (l) { l.classList.remove('active'); }); + link.classList.add('active'); + } + }); + }, { rootMargin: '-80px 0px -65% 0px', threshold: 0 }); + headings.forEach(function (h) { observerInst.observe(h); }); + } + + /* ──────────────────────────────────────────── reading progress */ + + function initProgressBar() { + window.addEventListener('scroll', updateProgressBar, { passive: true }); + window.addEventListener('resize', updateProgressBar); + } + + function updateProgressBar() { + var bar = document.getElementById('guide-progress'); + if (!bar) return; + var scroll = window.pageYOffset || document.documentElement.scrollTop; + var max = (document.documentElement.scrollHeight || document.body.scrollHeight) - window.innerHeight; + var pct = max > 0 ? (scroll / max) * 100 : 0; + bar.style.width = pct.toFixed(1) + '%'; + } + + /* ──────────────────────────────────────────── search */ + + function initSearch() { + var btn = document.getElementById('guide-search-trigger'); + var overlay = document.getElementById('guide-search-overlay'); + var input = document.getElementById('guide-search-input'); + var results = document.getElementById('guide-search-results'); + if (!overlay || !input || !results) return; + + if (btn) btn.addEventListener('click', openSearch); + + document.addEventListener('keydown', function (e) { + var modifier = e.metaKey || e.ctrlKey; + if (modifier && e.key.toLowerCase() === 'k') { + e.preventDefault(); + openSearch(); + return; + } + if (e.key === 'Escape' && state.searchOpen) { + e.preventDefault(); + closeSearch(); + } + if (state.searchOpen && (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Enter')) { + e.preventDefault(); + handleSearchNav(e.key); + } + }); + + overlay.addEventListener('click', function (e) { + if (e.target === overlay) closeSearch(); + }); + + input.addEventListener('input', function () { runSearch(input.value); }); + } + + function openSearch() { + state.searchOpen = true; + var overlay = document.getElementById('guide-search-overlay'); + var input = document.getElementById('guide-search-input'); + if (!overlay || !input) return; + overlay.classList.add('open'); + input.value = ''; + runSearch(''); + setTimeout(function () { input.focus(); }, 30); + } + + function closeSearch() { + state.searchOpen = false; + var overlay = document.getElementById('guide-search-overlay'); + if (overlay) overlay.classList.remove('open'); + } + + function runSearch(query) { + var results = document.getElementById('guide-search-results'); + if (!results) return; + var bag = (window.ForgeLMUserManuals || {})[state.lang] || (window.ForgeLMUserManuals || {}).en || {}; + var idx = window.ForgeLMUserManualsIndex || { sections: [] }; + var q = query.trim().toLowerCase(); + + // Build a flat list of {route, sectionTitle, pageTitle, snippet, score}. + var hits = []; + idx.sections.forEach(function (section) { + var sectionTitle = section.titles[state.lang] || section.titles.en; + section.pages.forEach(function (page) { + var route = section.id + '/' + page.id; + var pageTitle = page.titles[state.lang] || page.titles.en; + var doc = bag[route]; + if (!doc) return; + + var titleLow = pageTitle.toLowerCase(); + var headingsText = (doc.headings || []).map(function (h) { return h.text; }).join(' '); + var bodyTextLow = stripTags(doc.html).toLowerCase(); + var blob = (titleLow + ' ' + headingsText.toLowerCase() + ' ' + bodyTextLow); + + var score = 0; + if (!q) { + score = 1; // show all when query is empty + } else { + if (titleLow === q) score += 100; + if (titleLow.indexOf(q) !== -1) score += 50; + if (headingsText.toLowerCase().indexOf(q) !== -1) score += 20; + if (blob.indexOf(q) !== -1) score += 5; + // Multi-token: each token must appear somewhere + var tokens = q.split(/\s+/).filter(Boolean); + if (tokens.length > 1) { + var allMatch = tokens.every(function (t) { return blob.indexOf(t) !== -1; }); + if (allMatch) score += 10; + } + } + if (score === 0) return; + + hits.push({ + route: route, + sectionTitle: sectionTitle, + pageTitle: pageTitle, + score: score, + }); + }); + }); + + hits.sort(function (a, b) { return b.score - a.score; }); + hits = hits.slice(0, 12); + + if (!hits.length) { + results.innerHTML = '
No matches.
'; + } else { + results.innerHTML = hits.map(function (h, i) { + return '
  • ' + + '
    ' + escapeHtml(h.sectionTitle) + '
    ' + + '
    ' + highlight(h.pageTitle, q) + '
    ' + + '
  • '; + }).join(''); + // Re-translate after innerHTML update. + if (window.ForgeLMi18n && window.ForgeLMi18n.setLanguage) { + window.ForgeLMi18n.setLanguage(state.lang); + } + results.querySelectorAll('a').forEach(function (a) { + a.addEventListener('click', function (e) { + e.preventDefault(); + navigate(a.dataset.route, false); + }); + }); + } + } + + function handleSearchNav(key) { + var results = document.getElementById('guide-search-results'); + if (!results) return; + var links = Array.prototype.slice.call(results.querySelectorAll('a')); + if (!links.length) return; + var idx = links.findIndex(function (a) { return a.classList.contains('focused'); }); + if (key === 'ArrowDown') idx = Math.min(idx + 1, links.length - 1); + if (key === 'ArrowUp') idx = Math.max(idx - 1, 0); + if (key === 'Enter') { + if (idx >= 0) { + var route = links[idx].dataset.route; + if (route) navigate(route, false); + } + return; + } + links.forEach(function (a, i) { a.classList.toggle('focused', i === idx); }); + var fl = links[idx]; + if (fl) fl.scrollIntoView({ block: 'nearest' }); + } + + /* ──────────────────────────────────────────── lazy-load language data */ + + function ensureLangLoaded(lang) { + return new Promise(function (resolve, reject) { + if (state.loadedLangs[lang]) { resolve(); return; } + var existing = (window.ForgeLMUserManuals || {})[lang]; + if (existing) { + state.loadedLangs[lang] = true; + resolve(); + return; + } + var s = document.createElement('script'); + s.src = 'js/usermanuals/' + lang + '.js'; + s.onload = function () { state.loadedLangs[lang] = true; resolve(); }; + s.onerror = function () { reject(new Error('failed to load ' + lang)); }; + document.head.appendChild(s); + }); + } + + /* ──────────────────────────────────────────── language watcher */ + + function initLanguageWatcher() { + var initial = document.documentElement.lang || 'en'; + state.lang = initial; + var obs = new MutationObserver(function (muts) { + muts.forEach(function (m) { + if (m.attributeName === 'lang') { + var newLang = document.documentElement.lang || 'en'; + if (newLang !== state.lang) { + state.lang = newLang; + ensureLangLoaded(newLang).then(function () { + buildSidebar(); + renderCurrentRoute(); + }); + } + } + }); + }); + obs.observe(document.documentElement, { attributes: true }); + } + + /* ──────────────────────────────────────────── mobile drawer */ + + function initMobileDrawer() { + var btn = document.getElementById('guide-mobile-toggle'); + var sidebar = document.getElementById('guide-sidebar'); + if (!btn || !sidebar) return; + btn.addEventListener('click', function () { + sidebar.classList.toggle('open'); + }); + } + + function closeSidebar() { + var sidebar = document.getElementById('guide-sidebar'); + if (sidebar) sidebar.classList.remove('open'); + } + + function updateMobileCrumb(title) { + var el = document.getElementById('guide-mobile-crumb'); + if (el) el.textContent = title; + } + + /* ──────────────────────────────────────────── mermaid */ + + function initMermaid() { + if (!window.mermaid) return; + var theme = document.documentElement.getAttribute('data-theme') === 'light' ? 'default' : 'dark'; + try { + window.mermaid.initialize({ + startOnLoad: false, + theme: theme, + securityLevel: 'strict', + flowchart: { curve: 'basis', useMaxWidth: true }, + themeVariables: theme === 'dark' ? { + background: '#161a24', + primaryColor: '#1c2030', + primaryBorderColor: '#f97316', + primaryTextColor: '#e6e7ec', + lineColor: '#9ea3b3', + secondaryColor: '#11141c', + tertiaryColor: '#0a0c12', + fontFamily: 'Inter, sans-serif', + } : { + background: '#fafbfd', + primaryColor: '#ffffff', + primaryBorderColor: '#f97316', + primaryTextColor: '#0c0f17', + lineColor: '#4a5163', + fontFamily: 'Inter, sans-serif', + }, + }); + } catch (e) { /* mermaid older versions */ } + + // Re-init mermaid on theme toggle so diagrams pick up new colours. + var themeObs = new MutationObserver(function () { + var newTheme = document.documentElement.getAttribute('data-theme') === 'light' ? 'default' : 'dark'; + try { + window.mermaid.initialize({ startOnLoad: false, theme: newTheme }); + renderCurrentRoute(); + } catch (e) { /* ignore */ } + }); + themeObs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); + } + + /* ──────────────────────────────────────────── helpers */ + + function escapeHtml(s) { + if (s == null) return ''; + return String(s) + .replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') + .replace(/'/g, '''); + } + + function stripTags(html) { + var tmp = document.createElement('div'); + tmp.innerHTML = html; + return tmp.textContent || tmp.innerText || ''; + } + + function highlight(text, query) { + if (!query) return escapeHtml(text); + var lower = text.toLowerCase(); + var idx = lower.indexOf(query); + if (idx === -1) return escapeHtml(text); + var end = idx + query.length; + return escapeHtml(text.slice(0, idx)) + + '' + escapeHtml(text.slice(idx, end)) + '' + + escapeHtml(text.slice(end)); + } +})(); diff --git a/site/js/i18n.js b/site/js/i18n.js index 2946d57c..dbdb6e7b 100644 --- a/site/js/i18n.js +++ b/site/js/i18n.js @@ -44,8 +44,43 @@ } function lookup(table, key) { - if (!table) return undefined; - return Object.prototype.hasOwnProperty.call(table, key) ? table[key] : undefined; + // Object.hasOwn (ES2022) replaces the older + // Object.prototype.hasOwnProperty.call(...) pattern that static analyzers + // flag for prototype-method access. The bracket read on the next line is + // safe because we have just confirmed key is an own property of table — + // it cannot resolve to a prototype-chain pollution vector. + if (!table || typeof key !== 'string') return undefined; + return Object.hasOwn(table, key) ? table[key] : undefined; + } + + // Resolve the per-language sub-table without bracket access on a + // user-supplied key. Each branch returns a property by name so the + // analyzer can see no dynamic key reaches the object. + function tableForLang(all, lang) { + if (!all) return undefined; + switch (lang) { + case 'en': return all.en; + case 'tr': return all.tr; + case 'de': return all.de; + case 'fr': return all.fr; + case 'es': return all.es; + case 'zh': return all.zh; + default: return undefined; + } + } + + // Render a translation HTML fragment into a live element without using + // innerHTML directly. The translation values come from + // window.ForgeLMTranslations, which is generated at build time by + // tools/build_usermanuals.py from markdown files committed to the + // repository, so there is no runtime user-input path. DOMParser is + // used as defence-in-depth: even if a translation accidentally + // contained a @@ -31,17 +30,32 @@ ForgeLM - + + @@ -51,117 +65,20 @@