diff --git a/.dockerignore b/.dockerignore index 4f341af3323..2550d9bf66e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -17,6 +17,11 @@ __pycache__/ /mtp/ /models/ /Strata-data/ +# the folders docker/entrypoint.sh creates in a mounted data/ (a link to llama.cpp, the models, the keys): never part of a build (#3644) +/data/install/ +/data/state/ +/data/home/ +/data/Strata-data/ third_party/llama.cpp/ third_party/*.zip *.done diff --git a/.gitattributes b/.gitattributes index bd4b5d5278c..8a835e52c7b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,9 +4,27 @@ bench/prompts/** -text # launchers keep their platform line endings wherever the repository is cloned *.sh text eol=lf *.bat text eol=crlf +*.cmd text eol=crlf +*.ps1 text eol=crlf +bin/strata text eol=lf # copies of real packs' native_experts.txt, parsed byte for byte by tests/core/expert_layout_test.cpp tests/data/native_experts/** -text # the quant yardstick's text set: tokenized byte for byte (set.ids.json), never convert its line endings data/quant_quality/** -text + +# the license text is shipped and checked as LF text on every checkout +LICENSE text eol=lf + +# container scripts run in Linux: always LF +docker/*.sh text eol=lf +Dockerfile text eol=lf +docker/Dockerfile text eol=lf +docker/compose/* text eol=lf + +# Apple tools (codesign, plutil) read these: LF only, wherever the repository is cloned +*.plist text eol=lf + +# vendored KaTeX (serve/web/vendor): the files are hashed byte for byte (PROVENANCE.json), never convert their line endings. +serve/web/vendor/** -text diff --git a/.github/ISSUE_TEMPLATE/benchmark.yml b/.github/ISSUE_TEMPLATE/benchmark.yml new file mode 100644 index 00000000000..2d2514b75f1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/benchmark.yml @@ -0,0 +1,26 @@ +name: Benchmark +description: Share measurements from your machine, or report a problem with the benchmark tools +title: "[Benchmark] " +labels: ["benchmark"] +body: + - type: markdown + value: | + The title must start with **[Benchmark]**. Keep it, and add the GPU and model after it. + + To share a full report, follow the [community benchmark guide](https://github.com/Niko1221/Strata/blob/main/docs/COMMUNITY_BENCHMARKS.md) and open a results-only pull request. The standard protocol is a [draft](https://github.com/Niko1221/Strata/blob/main/docs/BENCHMARK_PROTOCOL.md); existing tools do not implement it yet. Include poor results and failed requests. + - type: textarea + id: what + attributes: + label: What did you measure, or what went wrong + description: Hardware (GPU and VRAM, CPU, RAM, OS), Strata version, model and quantization, the exact command, and the numbers. Paste the report or link the pull request. + validations: + required: true + - type: dropdown + id: reproduction-status + attributes: + label: Reproduction status + options: + - Measured locally + - Unconfirmed (I did not run it) + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 38aca058858..0e0b198d7fb 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,37 +1,101 @@ name: Bug report description: Something in Strata doesn't work as documented -title: "[Bug]: " +title: "[Area] " labels: ["bug"] body: - type: markdown value: | - Thanks for the report. + Thanks for the report. Please read [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md) first. - Please search the [open issues](https://github.com/Niko1221/Strata/issues?q=is%3Aissue+state%3Aopen) first — this may already be tracked. + Search the [open and closed issues](https://github.com/Niko1221/Strata/issues?q=is%3Aissue) first: this may already be tracked, and new evidence belongs in that thread. + + Write only what you saw. Do not guess at steps, errors, hardware or severity. + + **The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below. + - type: dropdown + id: area + attributes: + label: Area + description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits. + options: + - "[Engine] (speed, kernels, models, the server and API)" + - "[GUI] (the desktop app)" + - "[TUI] (the Terminal: strata launch, connect, monitor)" + - "[Benchmark] (measurements and reports)" + - "[Docs] (documentation)" + - "[Other] (anything else, including setup and installation)" + validations: + required: true + - type: dropdown + id: how + attributes: + label: Desktop app, Terminal or source? + options: + - Desktop app (Windows, Linux or Mac) + - Terminal (the `strata` command) + - Source (START-HERE.bat, setup.sh or a build) + - Docker + - Other + validations: + required: true - type: textarea id: what attributes: label: What happened - description: What you did, what you got, and what you expected instead. Paste the exact error text if there is one. If there's a set of steps or commands that reproduces it, put them here too. + description: What you did, what you got, and what you expected instead. Paste the exact error text if there is one. + validations: + required: true + - type: textarea + id: reproduce + attributes: + label: Smallest steps or command that reproduce it + description: The shortest list of steps that shows the problem. If you cannot make it happen again, say so here. + validations: + required: false + - type: dropdown + id: reproduction-status + attributes: + label: Reproduction status + options: + - Reproduced locally + - Unconfirmed static analysis (I read code or ran a scanner; I did not see it fail) + validations: + required: true + - type: input + id: version + attributes: + label: Strata version + description: "In the app: Settings > About. In the Terminal: `strata --version`. From source: the About tab of the web page, or `engine` in `GET /v1/status`, or the git commit." + placeholder: "Strata 0.2.10 · engine 0.1.56" validations: required: true - type: input id: hardware attributes: - label: Strata version, GPU, OS - description: The engine version is on the About tab, or in `GET /v1/status` under `engine`. - placeholder: "0.1.31 · RTX 5070 12GB · Windows 11" + label: Graphics card, memory and system + description: The card and its VRAM, the RAM of the PC, and the operating system. + placeholder: "RTX 5070 12 GB · 64 GB RAM · Windows 11" validations: required: true + - type: input + id: model + attributes: + label: Model, size and settings + description: The model and size you started, the context, and whether pictures were on. Write what is relevant. + placeholder: "Qwen3.8-Flash-Next IQ2_XS · 128K context · pictures on" + validations: + required: false - type: textarea id: log attributes: - label: Engine log - description: Drag in `strata-.log` from your Strata folder. Drag and drop works directly into this box. + label: Logs + description: | + The app: Settings > Engine > Diagnostics > View logs > Save logs, then drag the file in. The Terminal: paste the output of `strata doctor`. From source: drag in `strata-.log` from your Strata folder. + Remove API keys, passwords and private text first. validations: required: false - type: markdown value: | A couple of extras that help a lot: - - Check the [troubleshooting table](https://github.com/Niko1221/Strata/blob/main/docs/DETAILS.md#troubleshooting) first, many reports are already solved there. \ No newline at end of file + - Check the [troubleshooting page](https://github.com/Niko1221/Strata/blob/main/docs/TROUBLESHOOTING.md) first, many reports are already solved there. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 4c763b2acb9..be9cdf2e900 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,5 @@ blank_issues_enabled: true contact_links: - name: Troubleshooting and known issues - url: https://github.com/Niko1221/Strata/blob/main/docs/DETAILS.md#troubleshooting + url: https://github.com/Niko1221/Strata/blob/main/docs/TROUBLESHOOTING.md about: Symptom-to-fix table for crashes, out of memory, hangs, and port problems. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 2754274d96c..8a2b375e675 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -1,18 +1,41 @@ name: Feature request description: Suggest something new or an improvement -title: "[Feature]: " +title: "[Area] " labels: ["enhancement"] body: - type: markdown value: | - Explain what you want in plain language. + Explain what you want in plain language. For a large feature, a change to a default or a refactor, please agree the scope here first. Read [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md). + + **The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below. + - type: dropdown + id: area + attributes: + label: Area + description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits. + options: + - "[Engine] (speed, kernels, models, the server and API)" + - "[GUI] (the desktop app)" + - "[TUI] (the Terminal: strata launch, connect, monitor)" + - "[Benchmark] (measurements and reports)" + - "[Docs] (documentation)" + - "[Other] (anything else, including setup and installation)" + validations: + required: true - type: textarea id: idea attributes: label: What do you want to do? - description: Describe the goal rather than the implementation. If there's a workaround you use today, mention it. + description: Describe the goal rather than the implementation. Say who needs it and why. validations: required: true + - type: textarea + id: workaround + attributes: + label: What do you do today instead? + description: The workaround you use now, if there is one. + validations: + required: false - type: markdown value: | - All of this counts: model and architecture support, the server and API, the web app, multi-GPU and layer split, images and vision, MCP servers, setup and installation, and performance. \ No newline at end of file + All of this counts: model and architecture support, the server and API, the app and the Terminal, multi-GPU and layer split, images and vision, MCP servers, setup and installation, and performance. diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml index de8ef868318..345bf512643 100644 --- a/.github/ISSUE_TEMPLATE/question.yml +++ b/.github/ISSUE_TEMPLATE/question.yml @@ -1,11 +1,27 @@ name: Question description: Ask how to use Strata, or share a result -title: "Question: " +title: "[Area] " labels: ["question"] body: - type: markdown value: | - Not sure how to do something, or want to share numbers from your machine? Ask here. + Not sure how to do something, or want to share numbers from your machine? Ask here. To share a full benchmark, see [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md#share-a-benchmark). + + **The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below. + - type: dropdown + id: area + attributes: + label: Area + description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits. + options: + - "[Engine] (speed, kernels, models, the server and API)" + - "[GUI] (the desktop app)" + - "[TUI] (the Terminal: strata launch, connect, monitor)" + - "[Benchmark] (measurements and reports)" + - "[Docs] (documentation)" + - "[Other] (anything else, including setup and installation)" + validations: + required: true - type: textarea id: question attributes: @@ -13,10 +29,17 @@ body: description: What you're trying to do. Include your version, GPU, and OS if it affects the answer. validations: required: true + - type: textarea + id: tried + attributes: + label: What you tried + description: What you already did and where you got stuck. + validations: + required: false - type: textarea id: numbers attributes: label: Results (optional) description: Only if you ran a benchmark or measured speed. Model, quant, context, and the tok/s you get. validations: - required: false \ No newline at end of file + required: false diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index b8bef3fb4d7..688f7aba694 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,12 +1,30 @@ -## Title - -Issue: Resolves # +**The title must start with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], for example "[Engine] fix decode stop on long prompts" or "[GUI] keep the model list after a tab switch".** -## Summary - + -## What changed - +## Problem and result + -## Extra Notes - +## Related discussion + + +## Approach + + +## Validation + + +**Passed:** + + +**Failed:** + + +**Not run:** + + +## Limits + diff --git a/.github/scripts/item-check.js b/.github/scripts/item-check.js new file mode 100644 index 00000000000..b07b6350c13 --- /dev/null +++ b/.github/scripts/item-check.js @@ -0,0 +1,218 @@ +'use strict'; +// Format check for issues and pull requests (see CONTRIBUTING.md and .github/ISSUE_TEMPLATE/*.yml). +// Pure functions only: no network, no filesystem. Used by intake.yml and reopen.yml through reset-bot.js. + +const AREAS = ['Engine', 'GUI', 'TUI', 'Benchmark', 'Docs', 'Other']; +const TITLE_RE = new RegExp('^\\[(' + AREAS.join('|') + ')\\] \\S'); +const NO_ANSWER = /^(_no response_|none|n\/a|na|-|todo|tbd|\.|\?)$/i; +const NOT_RUN_LABELS = /^\*\*(passed|failed|not run)\s*:?\*\*\s*:?/gim; + +// Version the reopened work must be tested on. +const CURRENT_VERSION_RE = /\b0\.2\.\d+|0\.2\.0-beta/i; +// Any version or commit. +const ANY_VERSION_RE = /\bv?\d+\.\d+(\.\d+)*(-[a-z0-9.]+)?\b|\b[0-9a-f]{7,40}\b|\bcommit\b/i; +const HARDWARE_RE = /\b(rtx|gtx|geforce|quadro|tesla|radeon|rx ?\d|instinct|arc|a\d{3,4}|b\d{2,3}|apple|m[1-5]( pro| max| ultra)?|nvidia|amd|intel|gpu|cpu|vram|\d+ ?gb|ram|windows|linux|ubuntu|debian|fedora|arch|macos|mac os|wsl)\b/i; +const REVISION_RE = /0\.2\.\d|beta|\bmain\b|\b[0-9a-f]{7,40}\b/i; + +function stripComments(text) { + return String(text || '').replace(//g, ''); +} + +function hasAreaPrefix(title) { + return TITLE_RE.test(String(title || '')); +} + +// Issue forms render as "### Label\n\nvalue". Returns { label: value } for those headings. +function parseSections(body) { + const out = {}; + let cur = null; + for (const line of stripComments(body).split(/\r?\n/)) { + const m = /^#{1,6}\s+(.+?)\s*#*\s*$/.exec(line); + if (m) { + cur = m[1].trim(); + out[cur] = ''; + } else if (cur !== null) { + out[cur] += line + '\n'; + } + } + for (const k of Object.keys(out)) out[k] = out[k].trim(); + return out; +} + +function realText(value) { + const t = String(value || '').replace(NOT_RUN_LABELS, '').replace(/\s+/g, ' ').trim(); + return NO_ANSWER.test(t) ? '' : t; +} + +function findSection(sections, re) { + for (const k of Object.keys(sections)) if (re.test(k)) return { key: k, value: sections[k] }; + return null; +} + +// Required parts of each issue form: [display name, heading regex, minimum characters of real text]. +const FORMS = { + bug: { + detect: /what happened/i, + parts: [ + ['Area', /^area$/i, 2], + ['Desktop app, Terminal or source?', /desktop app, terminal or source/i, 2], + ['What happened', /what happened/i, 20], + ['Reproduction status', /reproduction status/i, 2], + ['Strata version', /strata version/i, 3], + ['Graphics card, memory and system', /graphics card|memory and system/i, 3], + ], + needsCurrentVersion: 'Strata version', + }, + feature: { + detect: /what do you want to do/i, + parts: [ + ['Area', /^area$/i, 2], + ['What do you want to do?', /what do you want to do/i, 20], + ], + }, + question: { + detect: /your question/i, + parts: [ + ['Area', /^area$/i, 2], + ['Your question', /your question/i, 15], + ], + }, + benchmark: { + detect: /what did you measure/i, + parts: [ + ['What did you measure, or what went wrong', /what did you measure/i, 30], + ['Reproduction status', /reproduction status/i, 2], + ], + needsCurrentVersionInBody: true, + }, +}; + +function checkIssue({ title, body, labels = [], mode = 'intake' }) { + const missing = []; + if (!hasAreaPrefix(title)) { + missing.push('Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] decode stops after 2 minutes".'); + } + const text = stripComments(body); + const sections = parseSections(text); + const labelSet = new Set(labels.map((l) => String(l).toLowerCase())); + const needCurrent = mode === 'reopen'; + + let formKey = null; + for (const [key, f] of Object.entries(FORMS)) { + if (findSection(sections, f.detect)) { formKey = key; break; } + } + + if (formKey) { + const form = FORMS[formKey]; + for (const [name, re, min] of form.parts) { + const s = findSection(sections, re); + if (!s || realText(s.value).length < min) missing.push('Fill in "' + name + '".'); + } + if (needCurrent && form.needsCurrentVersion) { + const s = findSection(sections, /strata version/i); + if (s && realText(s.value) && !CURRENT_VERSION_RE.test(s.value)) { + missing.push('Re-test on Strata 0.2.0-beta and put that version in "' + form.needsCurrentVersion + '". If it no longer happens, say so in a comment instead.'); + } + } + if (needCurrent && form.needsCurrentVersionInBody && !CURRENT_VERSION_RE.test(text)) { + missing.push('Say which Strata version you measured on. Re-measure on 0.2.0-beta if you can.'); + } + return { ok: missing.length === 0, missing, kind: formKey }; + } + + // Free-form text (older issues, blank issues). + const plain = realText(text); + const lenient = labelSet.has('enhancement') || labelSet.has('question'); + if (plain.length < (lenient ? 40 : 80)) { + missing.push('Describe it in the issue body: what happened, what you expected, and the exact error if there is one. The issue forms (New issue > Bug report) list what to include.'); + } + if (!lenient) { + if (!ANY_VERSION_RE.test(text)) missing.push('Add the Strata version (Settings > About, or `strata --version`).'); + else if (needCurrent && !CURRENT_VERSION_RE.test(text)) missing.push('Re-test on Strata 0.2.0-beta and name that version in the issue. If it no longer happens, say so in a comment instead.'); + if (!HARDWARE_RE.test(text)) missing.push('Add your graphics card with its VRAM, your RAM and your operating system.'); + } + return { ok: missing.length === 0, missing, kind: 'free-form' }; +} + +function checkPull({ title, body, mode = 'intake' }) { + const missing = []; + if (!hasAreaPrefix(title)) { + missing.push('Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] fix decode stop on long prompts".'); + } + const text = stripComments(body); + const sections = parseSections(text); + const problem = findSection(sections, /problem|result|summary|what.*change/i); + const validation = findSection(sections, /validation|testing|tests?\b|how.*tested/i); + + let valText = ''; + if (problem || validation) { + if (!problem || realText(problem.value).length < 20) missing.push('Fill in "Problem and result": what triggered the change, and how it behaves before and after.'); + if (!validation || realText(validation.value).length < 20) { + missing.push('Fill in "Validation": the exact commands, the revision and environment tested, what you saw. Keep Passed, Failed and Not run apart.'); + } else { + valText = validation.value; + } + } else { + const plain = realText(text); + if (plain.length < 150) { + missing.push('Describe the pull request: the problem and the result. The pull request template shows the parts (Problem and result, Related discussion, Approach, Validation, Limits).'); + } + if (!/(problem|result|before|after|fix|because|bug)/i.test(plain)) missing.push('Add "Problem and result": what triggered the change, and how it behaves before and after.'); + if (!/(validat|tested|passed|ran |built|build|not run)/i.test(plain)) missing.push('Add "Validation": the exact commands, the revision and environment tested, and what you saw.'); + valText = plain; + } + if (mode === 'reopen' && valText && !REVISION_RE.test(valText)) { + missing.push('Say in Validation which revision you tested: rebase on main (or 0.2.0-beta) and re-run your checks.'); + } + return { ok: missing.length === 0, missing, kind: 'pull' }; +} + +function checkItem({ isPull, ...rest }) { + return isPull ? checkPull(rest) : checkIssue(rest); +} + +function checklist(missing) { + return missing.map((m) => '- [ ] ' + m).join('\n'); +} + +const CONTRIB = 'https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md'; + +function intakeComment(isPull, missing) { + return [ + 'Thanks for the ' + (isPull ? 'pull request' : 'issue') + '. To keep the tracker readable, every item needs an area prefix in the title and the parts of the ' + (isPull ? 'pull request template' : 'issue form') + ' filled in. This one is missing:', + '', + checklist(missing), + '', + 'Edit the ' + (isPull ? 'pull request' : 'issue') + ' (title and description) and this note goes away on its own. If it is still missing parts in 5 days it will be closed, which is not a rejection: fix it and comment `/reopen`.', + '', + 'Details: [CONTRIBUTING.md](' + CONTRIB + ')', + ].join('\n'); +} + +function reopenMissingComment(isPull, missing) { + return [ + 'Not reopened yet. Still missing:', + '', + checklist(missing), + '', + 'Edit the ' + (isPull ? 'pull request' : 'issue') + ' and comment `/reopen` again. Details: [CONTRIBUTING.md](' + CONTRIB + ')', + ].join('\n'); +} + +function reopenOkComment(isPull) { + return 'Reopened, thank you. A maintainer will pick it up from here.' + (isPull ? ' If it conflicts with main, rebase it first; that speeds up review.' : ''); +} + +function staleComment(isPull) { + return [ + 'Closing this ' + (isPull ? 'pull request' : 'issue') + ' because it still did not follow the format after 5 days. That is housekeeping, not a rejection.', + '', + 'To bring it back: fix the title (area prefix) and the missing parts, then comment `/reopen`. A check runs and reopens it, or tells you what is still missing. See [CONTRIBUTING.md](' + CONTRIB + ').', + ].join('\n'); +} + +module.exports = { + AREAS, TITLE_RE, hasAreaPrefix, parseSections, stripComments, realText, + checkIssue, checkPull, checkItem, checklist, + intakeComment, reopenMissingComment, reopenOkComment, staleComment, +}; diff --git a/.github/scripts/item-check.test.js b/.github/scripts/item-check.test.js new file mode 100644 index 00000000000..c870f144c32 --- /dev/null +++ b/.github/scripts/item-check.test.js @@ -0,0 +1,192 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const c = require('./item-check'); +const bot = require('./reset-bot'); + +const bugForm = (over = {}) => { + const f = { + 'Area': '[Engine] (speed, kernels, models, the server and API)', + 'Desktop app, Terminal or source?': 'Terminal (the `strata` command)', + 'What happened': 'Decode stops after two minutes with "CUDA error 700". I expected it to continue.', + 'Smallest steps or command that reproduce it': '_No response_', + 'Reproduction status': 'Reproduced locally', + 'Strata version': 'Strata 0.2.0-beta · engine 0.1.45.3', + 'Graphics card, memory and system': 'RTX 5070 12 GB · 64 GB RAM · Windows 11', + ...over, + }; + return Object.entries(f).map(([k, v]) => `### ${k}\n\n${v}`).join('\n\n'); +}; + +test('title prefix', () => { + assert.ok(c.hasAreaPrefix('[Engine] fix decode')); + assert.ok(c.hasAreaPrefix('[Docs] x')); + assert.ok(!c.hasAreaPrefix('Engine fix')); + assert.ok(!c.hasAreaPrefix('[engine] fix')); + assert.ok(!c.hasAreaPrefix('[Engine]')); + assert.ok(!c.hasAreaPrefix('[Engine] ')); + assert.ok(!c.hasAreaPrefix('[Area] foo')); + assert.ok(!c.hasAreaPrefix('')); + assert.ok(!c.hasAreaPrefix(undefined)); +}); + +test('filled bug form passes in both modes', () => { + for (const mode of ['intake', 'reopen']) { + const r = c.checkIssue({ title: '[Engine] decode stops', body: bugForm(), labels: ['bug'], mode }); + assert.deepStrictEqual(r.missing, []); + assert.strictEqual(r.kind, 'bug'); + } +}); + +test('bug form: missing parts are named', () => { + const r = c.checkIssue({ title: 'decode stops', body: bugForm({ 'Strata version': '_No response_', 'What happened': 'bad' }) }); + assert.ok(!r.ok); + assert.ok(r.missing.some((m) => /title/i.test(m))); + assert.ok(r.missing.some((m) => m.includes('What happened'))); + assert.ok(r.missing.some((m) => m.includes('Strata version'))); +}); + +test('reopen needs a 0.2 version, intake does not', () => { + const body = bugForm({ 'Strata version': 'Strata 0.1.44' }); + assert.ok(c.checkIssue({ title: '[Engine] x y', body, mode: 'intake' }).ok); + const r = c.checkIssue({ title: '[Engine] x y', body, mode: 'reopen' }); + assert.ok(!r.ok); + assert.ok(r.missing.some((m) => m.includes('0.2.0-beta'))); +}); + +test('html comments and placeholders do not count', () => { + const r = c.checkIssue({ title: '[Engine] x y', body: bugForm({ 'What happened': '' }) }); + assert.ok(r.missing.some((m) => m.includes('What happened'))); +}); + +test('feature and question forms', () => { + const f = '### Area\n\n[GUI] (the desktop app)\n\n### What do you want to do?\n\nLet me pin a model to the top of the list in the app.'; + assert.ok(c.checkIssue({ title: '[GUI] pin models', body: f, mode: 'reopen' }).ok); + assert.ok(!c.checkIssue({ title: '[GUI] pin models', body: '### Area\n\n[GUI]\n\n### What do you want to do?\n\n_No response_' }).ok); + const q = '### Area\n\n[Other]\n\n### Your question\n\nHow do I move the model folder to another drive?'; + assert.ok(c.checkIssue({ title: '[Other] model folder', body: q }).ok); +}); + +test('free-form issue', () => { + const good = 'Strata 0.2.0-beta on an RTX 3060 12 GB with 32 GB RAM on Linux: the server hangs when I send two requests at once. Expected both to finish.'; + assert.ok(c.checkIssue({ title: '[Engine] hang on two requests', body: good, mode: 'reopen' }).ok); + assert.ok(!c.checkIssue({ title: '[Engine] hang', body: 'it crashes', mode: 'intake' }).ok); + const old = good.replace('0.2.0-beta', '0.1.40'); + assert.ok(c.checkIssue({ title: '[Engine] hang', body: old, mode: 'intake' }).ok); + assert.ok(!c.checkIssue({ title: '[Engine] hang', body: old, mode: 'reopen' }).ok); + assert.ok(c.checkIssue({ title: '[Other] idea', body: 'It would help if the app remembered my last model between runs, today I pick it again.', labels: ['enhancement'], mode: 'reopen' }).ok); +}); + +const prBody = (over = {}) => { + const p = { + problem: 'Decode stopped on prompts above 8k because the stop check read the wrong length. Now it continues.', + validation: '**Passed:** `ctest -R decode`, commit abcdef1, RTX 3060, 12 of 12.\n\n**Failed:** none observed\n\n**Not run:** HIP build', + ...over, + }; + return `## Problem and result\n\n${p.problem}\n\n## Related discussion\nnone\n\n## Approach\nFix the length.\n\n## Validation\n${p.validation}\n\n## Limits\nnone`; +}; + +test('filled PR passes', () => { + assert.deepStrictEqual(c.checkPull({ title: '[Engine] fix stop', body: prBody(), mode: 'reopen' }).missing, []); +}); + +test('untouched PR template fails', () => { + const tpl = '## Problem and result\n\n\n## Validation\n\n\n**Passed:**\n\n\n**Failed:**\n\n**Not run:**\n'; + const r = c.checkPull({ title: '[Engine] fix stop', body: tpl }); + assert.ok(!r.ok); + assert.ok(r.missing.some((m) => m.includes('Problem and result'))); + assert.ok(r.missing.some((m) => m.includes('Validation'))); +}); + +test('PR: empty body and bad title', () => { + const r = c.checkPull({ title: 'fix', body: null }); + assert.ok(!r.ok); + assert.ok(r.missing.length >= 2); +}); + +test('PR reopen needs a revision', () => { + const body = prBody({ validation: '**Passed:** I tried it and it worked for me on my machine, looked fine.' }); + assert.ok(c.checkPull({ title: '[Engine] x y', body, mode: 'intake' }).ok); + assert.ok(!c.checkPull({ title: '[Engine] x y', body, mode: 'reopen' }).ok); +}); + +test('free-form PR', () => { + const body = 'This fixes a crash when the context is above 8k, because the length was read from the wrong field. Before it aborted, after it continues. I built it on CUDA and ran the decode test, passed.'; + assert.ok(c.checkPull({ title: '[Engine] fix crash', body }).ok); + assert.ok(!c.checkPull({ title: '[Engine] fix crash', body: 'fixes stuff' }).ok); +}); + +test('messages', () => { + const m = c.intakeComment(false, ['a', 'b']); + assert.ok(m.includes('- [ ] a') && m.includes('/reopen') && m.includes('CONTRIBUTING.md')); + assert.ok(c.staleComment(true).includes('/reopen')); +}); + +// handlers with a fake GitHub client +function fake(calls, extra = {}) { + const rest = { + issues: { + getLabel: async () => ({}), + createLabel: async (a) => calls.push(['createLabel', a.name]), + addLabels: async (a) => calls.push(['addLabels', a.labels]), + removeLabel: async (a) => calls.push(['removeLabel', a.name]), + createComment: async (a) => calls.push(['comment', a.body]), + update: async (a) => calls.push(['update', a.state]), + get: async () => ({ data: extra.live }), + listEvents: async () => {}, + listForRepo: async () => {}, + }, + pulls: { get: async () => ({ data: { mergeable_state: 'clean' } }) }, + }; + return { rest, paginate: async (fn) => (fn === rest.issues.listEvents ? (extra.events || []) : (extra.items || [])) }; +} +const core = { info() {} }; +const repo = { owner: 'o', repo: 'r' }; + +test('intake labels and comments once', async () => { + const calls = []; + const item = { number: 1, title: 'bad', body: '', labels: [], user: { type: 'User' }, author_association: 'NONE' }; + await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'opened', issue: item } }, core }); + assert.deepStrictEqual(calls.map((c) => c[0]), ['addLabels', 'comment']); + calls.length = 0; + item.labels = [{ name: 'needs-format' }]; + await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'edited', issue: item } }, core }); + assert.deepStrictEqual(calls, []); +}); + +test('intake clears the label when edited into shape', async () => { + const calls = []; + const item = { number: 1, title: '[Engine] x y', body: bugForm(), labels: [{ name: 'needs-format' }], user: { type: 'User' } }; + await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'edited', issue: item } }, core }); + assert.deepStrictEqual(calls.map((c) => c[0]), ['removeLabel', 'comment']); +}); + +test('reopen: ignores strangers, reopens the author when it passes', async () => { + const issue = { number: 5, state: 'closed', user: { login: 'amy' }, labels: [] }; + let calls = []; + const comment = { body: '/reopen', user: { login: 'bob', type: 'User' }, author_association: 'NONE' }; + await bot.reopen({ github: fake(calls), context: { repo, payload: { issue, comment } }, core }); + assert.deepStrictEqual(calls, []); + + const live = { number: 5, title: '[Engine] x y', body: bugForm(), labels: [] }; + comment.user.login = 'amy'; + await bot.reopen({ github: fake(calls, { live }), context: { repo, payload: { issue, comment } }, core }); + assert.deepStrictEqual(calls.map((c) => c[0]), ['update', 'removeLabel', 'comment']); + assert.strictEqual(calls[0][1], 'open'); + + calls = []; + live.title = 'no prefix'; + await bot.reopen({ github: fake(calls, { live }), context: { repo, payload: { issue, comment } }, core }); + assert.deepStrictEqual(calls.map((c) => c[0]), ['comment']); + assert.ok(calls[0][1].includes('Not reopened')); +}); + +test('sweep closes only old flagged items', async () => { + const calls = []; + const old = new Date(Date.now() - 6 * 86400000).toISOString(); + const fresh = new Date(Date.now() - 1 * 86400000).toISOString(); + const mk = (n, created) => ({ number: n, title: 'bad', body: '', labels: [{ name: 'needs-format' }], created_at: created }); + const gh = fake(calls, { items: [mk(1, old), mk(2, fresh)] }); + await bot.sweep({ github: gh, context: { repo }, core }); + assert.deepStrictEqual(calls.map((c) => c[0]), ['comment', 'update']); +}); diff --git a/.github/scripts/reset-bot.js b/.github/scripts/reset-bot.js new file mode 100644 index 00000000000..11eb63ae3f6 --- /dev/null +++ b/.github/scripts/reset-bot.js @@ -0,0 +1,164 @@ +'use strict'; +// GitHub-side handlers for intake.yml, reopen.yml and the 5-day sweep. +// They take the actions/github-script objects ({ github, context, core }) and never touch PR code: +// everything comes from the event payload and the REST API. + +const check = require('./item-check'); + +const LABEL = 'needs-format'; +const STALE_DAYS = 5; +const MAINTAINER = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']); +// Items a maintainer closed on purpose stay closed. +const BLOCK_LABELS = new Set(['wontfix', 'invalid', 'duplicate', 'declined']); + +function labelNames(item) { + return (item.labels || []).map((l) => (typeof l === 'string' ? l : l.name)); +} + +async function ensureLabel(github, context) { + const { owner, repo } = context.repo; + try { + await github.rest.issues.getLabel({ owner, repo, name: LABEL }); + } catch (e) { + if (e.status !== 404) throw e; + await github.rest.issues.createLabel({ + owner, repo, name: LABEL, color: 'fbca04', + description: 'Title or description does not follow CONTRIBUTING.md yet', + }); + } +} + +async function removeLabel(github, context, number) { + const { owner, repo } = context.repo; + try { + await github.rest.issues.removeLabel({ owner, repo, issue_number: number, name: LABEL }); + } catch (e) { + if (e.status !== 404) throw e; + } +} + +function itemFromPayload(context) { + const p = context.payload; + return p.pull_request || p.issue; +} + +function isPullItem(item, context) { + return Boolean(context.payload.pull_request || item.pull_request); +} + +// issues: opened/edited/reopened, pull_request_target: opened/edited/reopened +async function intake({ github, context, core }) { + const { owner, repo } = context.repo; + const item = itemFromPayload(context); + if (!item || (item.user && item.user.type === 'Bot')) return; + if (MAINTAINER.has(item.author_association) && context.payload.action === 'opened') { + // Maintainer items are not nagged on creation. + return; + } + const isPull = isPullItem(item, context); + const labels = labelNames(item); + const hasLabel = labels.includes(LABEL); + const res = check.checkItem({ isPull, title: item.title, body: item.body, labels, mode: 'intake' }); + core.info('check ' + (isPull ? 'PR' : 'issue') + ' #' + item.number + ': ' + (res.ok ? 'ok' : res.missing.join(' | '))); + + if (res.ok) { + if (hasLabel) { + await removeLabel(github, context, item.number); + await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: 'Thanks, this follows the format now.' }); + } + return; + } + if (context.payload.action === 'edited' && !hasLabel) return; // edits only matter for items already flagged + if (hasLabel) return; // one note only + await ensureLabel(github, context); + await github.rest.issues.addLabels({ owner, repo, issue_number: item.number, labels: [LABEL] }); + await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: check.intakeComment(isPull, res.missing) }); +} + +// issue_comment created, body starts with /reopen +async function reopen({ github, context, core }) { + const { owner, repo } = context.repo; + const comment = context.payload.comment; + const issue = context.payload.issue; + if (!/^\s*\/reopen\b/.test(comment.body || '')) return; + if (comment.user.type === 'Bot') return; + const isAuthor = comment.user.login === issue.user.login; + const isMaint = MAINTAINER.has(comment.author_association); + if (!isAuthor && !isMaint) { + core.info('ignored /reopen from ' + comment.user.login + ' (not the author or a maintainer)'); + return; + } + const isPull = Boolean(issue.pull_request); + const say = (body) => github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body }); + const labels = labelNames(issue); + const wasOpen = issue.state === 'open'; + + if (labels.some((l) => BLOCK_LABELS.has(l.toLowerCase())) && !isMaint) { + await say('This one was closed on purpose (' + labels.filter((l) => BLOCK_LABELS.has(l.toLowerCase())).join(', ') + '). Please add your new evidence in a comment and a maintainer will decide.'); + return; + } + if (wasOpen && !labels.includes(LABEL)) { + core.info('already open, nothing to do'); + return; + } + + // The bot reads the live item, not the possibly stale event copy. + const live = (await github.rest.issues.get({ owner, repo, issue_number: issue.number })).data; + const res = check.checkItem({ isPull, title: live.title, body: live.body, labels: labelNames(live), mode: 'reopen' }); + core.info('reopen check #' + live.number + ': ' + (res.ok ? 'ok' : res.missing.join(' | '))); + + if (!res.ok) { + await say(check.reopenMissingComment(isPull, res.missing)); + return; + } + if (!wasOpen) { + try { + await github.rest.issues.update({ owner, repo, issue_number: live.number, state: 'open' }); + } catch (e) { + await say('The check passed, but GitHub would not reopen it (' + (e.message || e.status) + '). ' + (isPull ? 'If the branch was deleted, restore it or open a new pull request and link this one.' : 'Please open a new issue and link this one.')); + return; + } + } + await removeLabel(github, context, live.number); + let extra = ''; + if (isPull) { + try { + const pr = (await github.rest.pulls.get({ owner, repo, pull_number: live.number })).data; + if (pr.mergeable_state === 'dirty') extra = '\n\nIt has conflicts with main now: please rebase it.'; + } catch (e) { /* best effort */ } + } + await say(check.reopenOkComment(isPull) + extra); +} + +async function labelTime(github, owner, repo, number, fallback) { + const events = await github.paginate(github.rest.issues.listEvents, { owner, repo, issue_number: number, per_page: 100 }); + let t = null; + for (const e of events) { + if (e.event === 'labeled' && e.label && e.label.name === LABEL) t = e.created_at; + } + return t || fallback; +} + +// scheduled: close items that kept the needs-format label for more than 5 days +async function sweep({ github, context, core }) { + const { owner, repo } = context.repo; + const cutoff = Date.now() - STALE_DAYS * 86400 * 1000; + const items = await github.paginate(github.rest.issues.listForRepo, { owner, repo, state: 'open', labels: LABEL, per_page: 100 }); + core.info(items.length + ' open items with ' + LABEL); + for (const item of items) { + const since = new Date(await labelTime(github, owner, repo, item.number, item.created_at)).getTime(); + if (since > cutoff) continue; + const isPull = Boolean(item.pull_request); + // Re-check first: an edit that fixed it should have cleared the label already; do not close good items. + const res = check.checkItem({ isPull, title: item.title, body: item.body, labels: labelNames(item), mode: 'intake' }); + if (res.ok) { + await removeLabel(github, context, item.number); + continue; + } + await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: check.staleComment(isPull) }); + await github.rest.issues.update({ owner, repo, issue_number: item.number, state: 'closed', state_reason: 'not_planned' }); + core.info('closed #' + item.number); + } +} + +module.exports = { intake, reopen, sweep, LABEL, STALE_DAYS }; diff --git a/.github/workflows/docker-images.yml b/.github/workflows/docker-images.yml new file mode 100644 index 00000000000..ac0bf8a4eef --- /dev/null +++ b/.github/workflows/docker-images.yml @@ -0,0 +1,114 @@ +name: Docker images + +# Builds the Strata container images of one release from its engine packages and pushes them to ghcr.io. +# Run by hand only (Actions tab -> Docker images -> Run workflow). Nothing starts it on its own. +# +# For each flavor the job downloads the engine package from the release and checks it against the signed update feed +# (docker/fetch-engines.py: the feed's Ed25519 signature, the archive's SHA-256, the manifest hash, the package signature, +# every file's hash), builds the image with docker/build.sh and, only when "push" is on, pushes +# ghcr.io/niko1221/strata:- and ghcr.io/niko1221/strata:latest- +# The first run with "push" off builds everything without publishing it (a dry run). + +on: + workflow_dispatch: + inputs: + release_tag: + description: 'Release tag whose engine packages go into the images (for example v0.2.7)' + required: true + type: string + flavors: + description: 'Flavors to build, comma separated (empty: every flavor the release has a package for)' + required: false + default: '' + type: string + push: + description: 'Push the images to ghcr.io (off: build only, nothing is published)' + required: true + default: false + type: boolean + latest: + description: 'Also move the latest- tags (turn off for a pre-release or a test)' + required: true + default: true + type: boolean + source_ref: + description: 'Git ref of the Dockerfile and the Terminal sources (empty: the release tag)' + required: false + default: '' + type: string + +permissions: + contents: read + +env: + IMAGE: ghcr.io/niko1221/strata + +jobs: + plan: + runs-on: ubuntu-24.04 + outputs: + flavors: ${{ steps.list.outputs.flavors }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.source_ref || inputs.release_tag }} + - name: Which flavors does the release have a package for + id: list + env: + WANT: ${{ inputs.flavors }} + TAG: ${{ inputs.release_tag }} + run: | + set -eu + args="--release-tag $TAG --list --skip-missing" + [ -n "$WANT" ] && args="$args --flavors $WANT" + python3 docker/fetch-engines.py $args > list.tsv + cat list.tsv + flavors=$(awk -F'\t' '$3 != "SKIP" {printf "%s\"%s\"", (n++ ? "," : ""), $1}' list.tsv) + [ -n "$flavors" ] || { echo "the release has no engine package for any requested flavor"; exit 1; } + echo "flavors=[$flavors]" >> "$GITHUB_OUTPUT" + + image: + needs: plan + runs-on: ubuntu-24.04 + timeout-minutes: 120 + permissions: + contents: read + packages: write + strategy: + fail-fast: false + max-parallel: 3 + matrix: + flavor: ${{ fromJSON(needs.plan.outputs.flavors) }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.source_ref || inputs.release_tag }} + - name: Free disk space (the runner has about 14 GB; a package plus its image needs about 10 GB) + run: | + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL || true + docker system prune -af >/dev/null 2>&1 || true + df -h / + - name: Log in to ghcr.io + if: ${{ inputs.push }} + env: + REGISTRY_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REGISTRY_USER: ${{ github.actor }} + run: printf '%s' "$REGISTRY_TOKEN" | docker login ghcr.io -u "$REGISTRY_USER" --password-stdin + - name: Fetch, verify, build (and push when push is on) + env: + TAG: ${{ inputs.release_tag }} + FLAVOR: ${{ matrix.flavor }} + PUSH: ${{ inputs.push && '--push' || '' }} + LATEST: ${{ !inputs.latest && '--no-latest' || '' }} + run: | + docker/publish.sh --release-tag "$TAG" --flavors "$FLAVOR" --image "$IMAGE" $PUSH $LATEST + - name: Summary + if: ${{ always() }} + run: | + { + echo "### ${{ matrix.flavor }}" + echo "- release: ${{ inputs.release_tag }}, pushed: ${{ inputs.push }}" + echo "- image: \`$IMAGE:${INPUT_TAG#v}-${{ matrix.flavor }}\`" + } >> "$GITHUB_STEP_SUMMARY" + env: + INPUT_TAG: ${{ inputs.release_tag }} diff --git a/.github/workflows/intake.yml b/.github/workflows/intake.yml new file mode 100644 index 00000000000..326a0d9248e --- /dev/null +++ b/.github/workflows/intake.yml @@ -0,0 +1,58 @@ +name: Intake + +# New issues and pull requests that do not follow CONTRIBUTING.md get the needs-format label and one friendly note. +# Items that keep the label for 5 days are closed by the daily sweep, with a note on how to /reopen. +# +# pull_request_target is used instead of pull_request on purpose: a pull request from a fork gets a read-only +# GITHUB_TOKEN under pull_request, so it could not be labelled or commented on. It is safe here because this +# workflow never checks out or runs the pull request's code. It checks out the default branch only (the bot +# scripts) and reads the title and description from the event payload and the REST API. + +on: + issues: + types: [opened, edited] + pull_request_target: + types: [opened, edited] + schedule: + - cron: '17 4 * * *' + workflow_dispatch: + +permissions: + contents: read + issues: write + pull-requests: write + +concurrency: + group: intake-${{ github.event.issue.number || github.event.pull_request.number || 'sweep' }} + cancel-in-progress: false + +jobs: + check: + if: github.event_name == 'issues' || github.event_name == 'pull_request_target' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: .github/scripts + persist-credentials: false + - uses: actions/github-script@v7 + with: + script: | + const bot = require('./.github/scripts/reset-bot.js'); + await bot.intake({ github, context, core }); + + sweep: + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: .github/scripts + persist-credentials: false + - uses: actions/github-script@v7 + with: + script: | + const bot = require('./.github/scripts/reset-bot.js'); + await bot.sweep({ github, context, core }); diff --git a/.github/workflows/metal-build.yml b/.github/workflows/metal-build.yml new file mode 100644 index 00000000000..a4f7d997046 --- /dev/null +++ b/.github/workflows/metal-build.yml @@ -0,0 +1,53 @@ +name: Metal build + +# Compile and link the Metal engine on a macOS runner (no GPU needed: the kernels are compiled at run time). The shared host files +# (src/core/verify.cpp, src/prefill, src/program/generate.cpp) call kernel entry points that exist only for CUDA / HIP until Metal gets a +# stub or an implementation; a missing one is a link error here, not on a user's Mac (owner round 9, G6). + +on: + pull_request: + paths: + - 'src/**' + - 'include/**' + - 'metal/**' + - 'third_party/**' + - 'CMakeLists.txt' + - '.github/workflows/metal-build.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + metal-link: + # the macOS 26 SDK: metal/src/mtl_rt.mm names MTLGPUFamilyMetal4 (and MTLCompileOptions.mathMode, macOS 15) behind @available, + # which is a run-time check; the names must still be in the SDK the engine is compiled against + runs-on: macos-26 + timeout-minutes: 45 + env: + # setup.py's LLAMA_CPP_COMMIT and metal/setup_mac.py's metal-cpp pin + LLAMA_CPP_COMMIT: 3cf03257f219afbe7334045ff7c6a06ac68c627d + METAL_CPP_URL: https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip + METAL_CPP_SHA256: 4df3c078b9aadcb516212e9cb03004cbc5ce9a3e9c068fa3144d021db585a3a4 + steps: + - uses: actions/checkout@v4 + - name: Tools + run: brew install ninja + - name: metal-cpp + run: | + curl -fsSL "$METAL_CPP_URL" -o metal-cpp.zip + echo "$METAL_CPP_SHA256 metal-cpp.zip" | shasum -a 256 -c - + unzip -q metal-cpp.zip -d _mcpp + - name: llama.cpp (ggml) at the pinned commit + run: | + mkdir llama.cpp && cd llama.cpp + git init -q + git remote add origin https://github.com/ggml-org/llama.cpp.git + git fetch -q --depth 1 origin "$LLAMA_CPP_COMMIT" + git checkout -q FETCH_HEAD + - name: Configure + run: | + cmake -S metal -B build-metal -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DMETAL_CPP_DIR="$PWD/_mcpp/metal-cpp" -DSTRATA_GGML_DIR="$PWD/llama.cpp" + - name: Build and link the engine + run: cmake --build build-metal --target strata diff --git a/.github/workflows/reopen.yml b/.github/workflows/reopen.yml new file mode 100644 index 00000000000..ff7c10f9a92 --- /dev/null +++ b/.github/workflows/reopen.yml @@ -0,0 +1,38 @@ +name: Reopen + +# An author comments /reopen on their closed issue or pull request. The check runs and the item is reopened, +# or the bot replies with what is still missing. GitHub does not let authors reopen items a maintainer closed, +# so this workflow does it for them. +# +# issue_comment always runs the workflow file from the default branch with a write-capable token, which is what +# we need for fork authors too. It never checks out or executes the pull request's code: it reads the live +# title and description through the REST API. Only the author of the item or a maintainer can trigger it. + +on: + issue_comment: + types: [created] + +permissions: + contents: read + issues: write + pull-requests: write + +concurrency: + group: reopen-${{ github.event.issue.number }} + cancel-in-progress: false + +jobs: + reopen: + if: startsWith(github.event.comment.body, '/reopen') && github.event.comment.user.type != 'Bot' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: .github/scripts + persist-credentials: false + - uses: actions/github-script@v7 + with: + script: | + const bot = require('./.github/scripts/reset-bot.js'); + await bot.reopen({ github, context, core }); diff --git a/.github/workflows/scripts-test.yml b/.github/workflows/scripts-test.yml new file mode 100644 index 00000000000..97b5de9c0fc --- /dev/null +++ b/.github/workflows/scripts-test.yml @@ -0,0 +1,21 @@ +name: Scripts test + +on: + pull_request: + paths: + - '.github/scripts/**' + - '.github/workflows/intake.yml' + - '.github/workflows/reopen.yml' + +permissions: + contents: read + +jobs: + node-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: node --test .github/scripts/item-check.test.js diff --git a/.github/workflows/terminal-minimal-server.yml b/.github/workflows/terminal-minimal-server.yml new file mode 100644 index 00000000000..e2c753161db --- /dev/null +++ b/.github/workflows/terminal-minimal-server.yml @@ -0,0 +1,65 @@ +name: Minimal serving runtime + +on: + push: + paths: + - .github/workflows/terminal-minimal-server.yml + - requirements.txt + - strata.py + - strata_cli/** + - strata_control/** + - serve/** + - tests/terminal/test_runtime.py + - tools/minimal_server_smoke.py + - tools/strata_tokenizer.py + pull_request: + paths: + - .github/workflows/terminal-minimal-server.yml + - requirements.txt + - strata.py + - strata_cli/** + - strata_control/** + - serve/** + - tests/terminal/test_runtime.py + - tools/minimal_server_smoke.py + - tools/strata_tokenizer.py + workflow_dispatch: + +permissions: + contents: read + +jobs: + fake-engine: + name: Linux / runtime requirements only + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-python@v7 + with: + python-version: '3.11' + - name: Install only pinned runtime requirements + shell: bash + run: | + python -m venv "$RUNNER_TEMP/strata-runtime-venv" + "$RUNNER_TEMP/strata-runtime-venv/bin/python" -m pip install -r requirements.txt + - name: Check fake-engine serving without terminal packages + shell: bash + run: | + python - <<'PY' + import os + import subprocess + from pathlib import Path + + report = Path(os.environ['RUNNER_TEMP']) / 'minimal-server-smoke.json' + python = str(Path(os.environ['RUNNER_TEMP']) / 'strata-runtime-venv' / 'bin' / 'python') + subprocess.run([python, 'tools/minimal_server_smoke.py', + '--report', str(report)], check=True) + print(report.read_text()) + PY + - name: Run full server suite without terminal packages + shell: bash + run: | + "$RUNNER_TEMP/strata-runtime-venv/bin/python" -m unittest discover -s serve -p 'test_*.py' diff --git a/.github/workflows/terminal-portable-monitor.yml b/.github/workflows/terminal-portable-monitor.yml new file mode 100644 index 00000000000..905e7c40f0a --- /dev/null +++ b/.github/workflows/terminal-portable-monitor.yml @@ -0,0 +1,115 @@ +name: Portable monitor client + +on: + push: + paths: + - .github/workflows/terminal-portable-monitor.yml + - packaging/monitor_bundle.py + - strata.py + - strata_cli/** + - strata_control/** + - tools/minimal_cli_smoke.py + - tools/portable_monitor_smoke.py + - tools/portable_monitor_pty_smoke.py + - requirements-monitor.txt + - LICENSE + pull_request: + paths: + - .github/workflows/terminal-portable-monitor.yml + - packaging/monitor_bundle.py + - strata.py + - strata_cli/** + - strata_control/** + - tools/minimal_cli_smoke.py + - tools/portable_monitor_smoke.py + - tools/portable_monitor_pty_smoke.py + - requirements-monitor.txt + - LICENSE + workflow_dispatch: + +permissions: + contents: read + +jobs: + client: + name: ${{ matrix.os }} / Python ${{ matrix.python }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + python: ['3.10', '3.11'] + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-python@v7 + with: + python-version: ${{ matrix.python }} + - name: Check source CLI without optional packages + shell: bash + run: | + python - <<'PY' + import os + import subprocess + import sys + from pathlib import Path + + report = Path(os.environ['RUNNER_TEMP']) / 'minimal-cli-smoke.json' + subprocess.run([sys.executable, 'tools/minimal_cli_smoke.py', + '--report', str(report)], check=True) + print(report.read_text()) + PY + - name: Build and smoke test without site packages + shell: bash + run: | + python - <<'PY' + import os + import subprocess + import sys + from pathlib import Path + + bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz' + report = bundle.with_name('monitor-stdlib-smoke.json') + subprocess.run([sys.executable, 'packaging/monitor_bundle.py', + 'build', str(bundle)], check=True) + subprocess.run([sys.executable, 'tools/portable_monitor_smoke.py', + '--bundle', str(bundle), '--report', str(report)], check=True) + print(report.read_text()) + PY + - name: Install optional Textual dependency + if: matrix.python == '3.11' + run: python -m pip install -r requirements-monitor.txt + - name: Smoke test packaged interactive Overview + if: matrix.python == '3.11' + shell: bash + run: | + python - <<'PY' + import os + import subprocess + import sys + from pathlib import Path + + bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz' + report = bundle.with_name('monitor-interactive-smoke.json') + subprocess.run([sys.executable, 'tools/portable_monitor_smoke.py', + '--bundle', str(bundle), '--interactive', + '--report', str(report)], check=True) + print(report.read_text()) + PY + - name: Check POSIX terminal restoration + if: matrix.os == 'ubuntu-latest' && matrix.python == '3.11' + shell: bash + run: | + python - <<'PY' + import os + import subprocess + import sys + from pathlib import Path + + bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz' + report = bundle.with_name('monitor-pty-smoke.json') + subprocess.run([sys.executable, 'tools/portable_monitor_pty_smoke.py', + '--bundle', str(bundle), '--report', str(report)], check=True) + print(report.read_text()) + PY diff --git a/.github/workflows/title-area.yml b/.github/workflows/title-area.yml new file mode 100644 index 00000000000..6c5779f0077 --- /dev/null +++ b/.github/workflows/title-area.yml @@ -0,0 +1,28 @@ +name: Title area + +# Checks that a pull request or issue title starts with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. +# It reads the title only: no checkout, no labels, no comments, no write access. + +on: + pull_request: + types: [opened, edited, reopened, synchronize] + issues: + types: [opened, edited, reopened] + +permissions: {} + +jobs: + title: + runs-on: ubuntu-latest + steps: + - name: Check the title + env: + TITLE: ${{ github.event.pull_request.title || github.event.issue.title }} + run: | + case "$TITLE" in + "[Engine] "?*|"[GUI] "?*|"[TUI] "?*|"[Benchmark] "?*|"[Docs] "?*|"[Other] "?*) + echo "Title OK: $TITLE" ;; + *) + echo "::error::The title must start with its area and then a short description. Allowed areas: [Engine], [GUI], [TUI], [Benchmark], [Docs], [Other]. Example: \"[Engine] fix decode stop on long prompts\". Your title: $TITLE" + exit 1 ;; + esac diff --git a/.gitignore b/.gitignore index c8837367af6..65457fdc042 100644 --- a/.gitignore +++ b/.gitignore @@ -48,6 +48,7 @@ build-vision-cuda12.bat # setup.py outputs (engine, downloads) and release builds /engine/ +/engine-sycl/ /engine-cuda12/ /build-release*/ /dist/ @@ -62,5 +63,35 @@ build-vision-cuda12.bat /.ccache/ /.rocm-win/ +# Optional MCP raster cache +*.tool-media/ +/.tool-media/ + # local Windows HIP packaging output dist-hip/ + +# Terminal / Desktop split: local venvs, build output and archives never enter git +.terminal-venv/ +.terminal-test-venv/ +node_modules/ +*.dmg +/release/artifacts/ +/apps/host/dist/ +/apps/desktop/src-tauri/target/ +/apps/desktop/src-tauri/resources/node/* +!/apps/desktop/src-tauri/resources/node/.gitignore +# the Control component (bundled CPython + wheels + strata_control) is built by apps/desktop/scripts/stage-control.py +/apps/desktop/src-tauri/resources/control/* +!/apps/desktop/src-tauri/resources/control/.gitignore +# the pruned DeepSeek Harness (MIT) is built by apps/desktop/scripts/stage-harness.mjs +/apps/desktop/src-tauri/resources/harness/* +!/apps/desktop/src-tauri/resources/harness/.gitignore +# screenshots and checkpoints from the Mac rebuild live outside git (StrataSplit\evidence-archive) +/apps/host/docs/evidence/ +/apps/host/docs/checkpoints/ + +# DGX Spark build outputs and local venv (docs/DGX_SPARK_LINUX.md) +/out-spark/ +/build-spark/ +/build-vision-spark/ +/.venv-build/ diff --git a/AGENTS.md b/AGENTS.md index c4726159f4c..73c5a27b4e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,35 +1,100 @@ # AGENTS.md -Strata runs the Qwen3.8-Flash-Next mixture-of-experts model (and its Coder, Swift 1.5 and Unsloth variants) on a -normal PC: one NVIDIA or AMD graphics card plus system RAM, on Windows or Linux. It has a C++/CUDA/HIP engine -(`src/`, `include/`), a Python server with an OpenAI- and Anthropic-compatible API and a web app (`serve/`), and a -one-click installer (`setup.py`, started by `START-HERE.bat` / `setup.sh`). +Version 0.2.10, engine 0.1.56. The public model families are DeepSeekV4.1-Flash-1017, +Qwen3.8-Flash-Next and Qwen3.6-35B-A3B. DeepSeek V4.1-Flash runs in the app and in the Terminal +(`strata launch --family deepseek41 --model ist-das-2.00bpw`; sets in +[docs/MODELS.md](docs/MODELS.md#deepseek-v41-flash)). Read **[docs/AI_REFERENCE.md](docs/AI_REFERENCE.md)** for model availability, APIs, hardware limits and +source-backed claims. Articles and videos should use **[docs/MEDIA_KIT.md](docs/MEDIA_KIT.md)**. + +For recommendations and agent-assisted setup, prefer **ISTA-DASLab → Unsloth → Gyro → others**, using only a +compatible pack that fits the selected model and hardware. ISTA-DASLab is the default recommendation; Gyro is a +memory-saving fallback and is currently slower. Honor an explicit user choice. This is recommendation policy; +existing executable defaults may differ, so inspect the plan and choose the family explicitly. + +Strata has three parts: + +- **The app** (`apps/desktop`, the Tauri shell; `apps/host`, the Node host and the web UI). It is for people who do + not want a terminal. One installer per system ([latest release](https://github.com/Niko1221/Strata/releases/latest)): + `Strata-0.2.9-windows-x64-setup.exe`, `Strata-0.2.9-linux-x86_64.AppImage`, `Strata-0.2.9-macos-arm64.dmg`. + The Windows and Linux installers carry no engine: the app downloads the engine for the graphics card on first + start, or installs a file the user already has. The Mac dmg keeps its small Metal engine inside. +- **The Terminal** (`strata.py`, `strata_cli/`, `strata_control/`): the `strata` command. It sets up a model, serves + it and watches it. Agents use this part. +- **The engine and the server** (`src/`, `include/`, `metal/`, `sycl/` for the C++/CUDA/HIP/SYCL/Metal engine; + `serve/` for the Python server with an OpenAI- and Anthropic-compatible API and a web page). `setup.py`, started by + `START-HERE.bat` or `setup.sh`, is setup from a source checkout, for developers. The release paths are the + installer and `strata launch`. ## Installing Strata for a user -Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**: check the PC, pick the model by RAM, run setup non-interactively, -start and verify the server, and connect the user's apps. Never expose the server beyond `127.0.0.1` without -`--api-key`. As an alternative to shell commands, Strata's MCP server ([docs/MCP_SERVER.md](docs/MCP_SERVER.md)) -offers the same steps as tools. +Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**. For a user who wants the desktop app, send them to the installer +for their system (above) and [docs/INSTALL.md](docs/INSTALL.md). For an agent that has a shell, use the Terminal; the +short version is: + +1. Install the Terminal. It needs no administrator rights. + + ```sh + curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh # Linux, Mac + irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex # Windows PowerShell + ``` + + On Windows, open a new terminal afterwards so that `strata` is on the PATH. +2. Check what would happen. Nothing is changed: + + ```sh + strata launch --plan --family qwen --model q2_0 + ``` + +3. Set up and serve without questions. It downloads the engine for the card and the model (tens of GB), starts the + server, prints the addresses and returns. The server keeps running. + + ```sh + strata launch --family qwen --model q2_0 --yes --no-tui + ``` + + Useful flags (all of them: `strata launch --help`): `--family`, `--model-path` (files the user already has), + `--data-dir`, `--context 32k|64k|128k`, `--vision off|on|gpu|cpu`, `--parallel N`, `--gpu 0,1`, + `--access local|lan|cloudflare|tailscale`, `--port`, `--api-key-env NAME`, `--new-key`, `--save-preset NAME`, + `--speed faster|full` (DeepSeek), `--output json`. `strata launch --status` shows what is serving, `strata launch --stop` stops it, and + `strata launch --show-key` prints the API key. +4. Connect the user's apps: `strata connect` lists them, `strata connect --check` sends one prompt and one tool + call the way that app does. + +Keep the server on `127.0.0.1` unless the user asks for more. Beyond it an API key is recommended: `--access lan` makes one for you, and `--no-api-key` serves without one (a warning, never a refusal; on a public tunnel the warning is stronger). Source setup (`START-HERE.bat`, `setup.sh`) is the fallback for a developer or for a system with no release package; it is +documented in [docs/SOURCE_INSTALL.md](docs/SOURCE_INSTALL.md). Those wrappers exist in a source checkout, not in the +released app. Do not tell an app user to find a `.bat` file. +Source setup does not make an unsupported model or backend compatible. Strata's MCP server ([docs/MCP_SERVER.md](docs/MCP_SERVER.md)) offers the same steps as tools. ## Working on the code - How the engine works, every measured number, the API and all settings: [docs/DETAILS.md](docs/DETAILS.md) and the [paper](docs/paper/Strata-Paper.pdf). -- AMD (HIP) build and validation: [docs/AMD_HIP.md](docs/AMD_HIP.md); multi-GPU: [docs/MULTI_GPU.md](docs/MULTI_GPU.md). -- Setup's own tests run without a GPU or downloads: `python tools/test_setup_.py` (for example - `tools/test_setup_amd.py`, `tools/test_setup_choices.py`). -- Keep the docs' style: plain words, measured numbers with what they were measured on, no claims without a - measurement. +- The Terminal: [docs/TERMINAL.md](docs/TERMINAL.md) and [docs/TERMINAL_LAUNCH.md](docs/TERMINAL_LAUNCH.md). The app, + the packages and the update feed: [packaging/README.md](packaging/README.md) and [packaging/UPDATES.md](packaging/UPDATES.md). +- AMD (HIP) build and validation: [docs/AMD_HIP.md](docs/AMD_HIP.md); multi-GPU: [docs/MULTI_GPU.md](docs/MULTI_GPU.md); + Mac (Metal): [docs/MAC.md](docs/MAC.md). +- Tests: the Terminal and Control tests are in `tests/terminal` (`python -m pytest tests/terminal`). The app's UI + tests run with `npm test` in `apps/host`. Setup's own tests run without a GPU or downloads: + `python tools/test_setup_.py` (for example `tools/test_setup_amd.py`, `tools/test_setup_choices.py`). +- Keep the docs' style: plain words, short sentences, written for non-technical users first. Give measured numbers + with what they were measured on. Make no claim without a measurement. ## Contributing a change or report -- Search the open issues and pull requests first, and add to a thread that already covers your point. -- Open an issue with the form that fits (bug report, feature request or question). -- One change per pull request. Say what it changes and what it leaves alone. +The rules are in **[CONTRIBUTING.md](CONTRIBUTING.md)**. Read it before you open an issue or a pull request, and +follow it whether a person or an agent writes the text. The short version: + +- Start every issue and pull request title with its area: `[Engine]`, `[GUI]`, `[TUI]`, `[Benchmark]`, `[Docs]` or + `[Other]`, for example `[Engine] fix …`. A check on GitHub fails a pull request whose title has no area. +- Search the open and closed issues and pull requests first, and add to a thread that already covers your point. +- Agree the scope in an issue before a large feature, a refactor or a change to a default. +- One problem per pull request. Lead with the problem and the result, then the approach, then the validation + (passed, failed and not run, kept apart) and the limits. - A new feature is opt-in, and the default path stays byte-identical to the last release. Say how you checked. - Build every backend a file touches (CUDA, HIP, SYCL) before asking for review. - Change a default only where you measured it faster, and show the numbers with what they were measured on. +- Never submit measurements, logs or reproduction steps you did not produce. Mark a finding from reading code as + unconfirmed static analysis. - A report from hardware the maintainers do not have is welcome. Follow [docs/COMMUNITY_BENCHMARKS.md](docs/COMMUNITY_BENCHMARKS.md), compare against a same-day run of the build you are testing, and say what you did not test. diff --git a/BENCH.bat b/BENCH.bat index 8d1ed0e8166..f54bc90dcd7 100644 --- a/BENCH.bat +++ b/BENCH.bat @@ -2,6 +2,7 @@ rem Benchmark this Strata install the way it is used and write a report you can share (docs/COMMUNITY_BENCHMARKS.md). rem It starts the model with your settings (or uses the one already running), takes about 10 minutes and changes nothing. rem Options: --clients 4 (several requests at once), --long (a 32K prompt), --compare . +rem This is the quick speed check. The standard benchmark (docs/BENCHMARK_PROTOCOL.md), whose results other people can compare with, is `strata bench run`. setlocal title Strata - benchmark cd /d "%~dp0" @@ -10,6 +11,8 @@ if not exist ".venv\Scripts\python.exe" ( pause exit /b 1 ) +echo Quick speed check. For results other people can compare with (the standard benchmark, a few minutes), run: .venv\Scripts\python.exe strata.py bench run +echo. ".venv\Scripts\python.exe" tools\strata_bench.py %* set "RC=%ERRORLEVEL%" pause diff --git a/CMakeLists.txt b/CMakeLists.txt index d900326e3dd..8659bf89c4d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -# Strata Engine - top-level build (P1.S1). +# Strata Engine - top-level build (P1.S1). # # Targets (phase-1 §P1.S1): `strata_artifact` (no CUDA dependency), `tests`. `strata_plan` and the C++ # `strata-pack` are added when their sources exist - a target with no sources would make the build graph @@ -8,7 +8,7 @@ # below refuses anything older: silently building for a pre-Ampere arch would produce a binary that runs # and is wrong about its own performance, which is the worst of both outcomes. cmake_minimum_required(VERSION 3.24) -project(strata VERSION 0.1.45 LANGUAGES CXX) +project(strata VERSION 0.1.56 LANGUAGES CXX) # EXPERIMENTAL: the Intel Arc engine, the SYCL port in sycl/ (PR #423; icpx + oneMKL, docs/INTEL_ARC.md). It is its # own project that takes the unported sources from src/; with this on, nothing below is configured. option(STRATA_ENABLE_SYCL "EXPERIMENTAL: build the Intel Arc (SYCL) engine from sycl/ - docs/INTEL_ARC.md" OFF) @@ -48,6 +48,28 @@ if(STRATA_PORTABLE AND MSVC) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded") endif() +# #3202: Windows hands a program its command line in the system's ANSI code page (cp1251 / cp866 on a Russian Windows, cp1252 on an +# English one), but the engine reads every path as UTF-8 (the run configs and the server write UTF-8). A model folder with +# Cyrillic letters arrived as other bytes, or as "?" where the page has no such letter, and the model did not open. This manifest +# makes the process's ANSI code page UTF-8 (Windows 10 1903 and newer; older Windows ignores it and nothing changes), so the +# command line, fopen and std::ifstream all take UTF-8. +function(strata_utf8_manifest target) + if(MSVC) + target_sources(${target} PRIVATE ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/cmake/strata-utf8.manifest) + endif() +endfunction() + +# The AVX kernels exist for x86 only. On aarch64 (DGX Spark / GB10) portable.cpp stands in for them and +# native experts run on ggml-cpu's NEON dot products. +if(NOT CMAKE_SYSTEM_PROCESSOR OR CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64|x64|X64|i[3-6]86|x86|X86)$") # an unset processor stays the x86 build, as before + set(STRATA_CPU_X86 ON) +else() + set(STRATA_CPU_X86 OFF) +endif() +if(STRATA_ISA_FLOOR AND NOT STRATA_CPU_X86) + message(WARNING "STRATA_ISA_FLOOR is an x86 older-CPU build and does not apply to ${CMAKE_SYSTEM_PROCESSOR}; ignored") + set(STRATA_ISA_FLOOR "" CACHE STRING "" FORCE) +endif() set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) @@ -70,12 +92,45 @@ if(STRATA_HIP_GFX906) endif() option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1012/gfx1030 unvalidated)" OFF) option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) +# The community-made AMD changes (include/strata/core/amd_community.hpp): on by default. This option is the build half of the one +# switch STRATA_AMD_COMMUNITY_TUNING: OFF compiles the portable signed-byte dot for gfx1010 again (the SDWA sequence of #4855). +# The rocBLAS tables are switched at run time (STRATA_AMD_COMMUNITY_TUNING=0). +option(STRATA_AMD_COMMUNITY_TUNING "Compile the community-made gfx1010 SDWA dot product (the runtime switch of the same name controls the gfx1030 rocBLAS tables)" ON) +if(NOT STRATA_AMD_COMMUNITY_TUNING) + add_compile_definitions(STRATA_AMD_COMMUNITY_DOT_OFF=1) +endif() +# The rows one verify / batch window holds (include/strata/kernels/window_limits.hpp): 8, the 0.2.7 window, or 16 (four pipelined +# groups of 16 slots = 64 slots on a four-card split, docs/BATCHING.md). Only the CUDA and HIP engines are built from +# these sources with a wide window; the SYCL and Metal builds never read this variable and keep 8. A window of up to +# 8 rows runs the kernels it always ran, whichever is chosen (the wide instantiations are extra code). "auto" = 16 for +# the HIP engines (a HIP code object loads on first use, so the extra kernels cost nothing until a wide window forms) +# and 8 for CUDA, which loads every kernel at start (CUDA_MODULE_LOADING=EAGER: the wide kernels would take VRAM from +# the expert cache of every card); -DSTRATA_WINDOW_MAX_T=16 builds the wide CUDA engine. +set(STRATA_WINDOW_MAX_T "auto" CACHE STRING "rows of a verify / batch window: 8, 12, 16 or auto (HIP 16, CUDA 8)") +set_property(CACHE STRATA_WINDOW_MAX_T PROPERTY STRINGS auto 8 12 16) +if(NOT STRATA_WINDOW_MAX_T STREQUAL "auto" AND NOT STRATA_WINDOW_MAX_T STREQUAL "8" AND NOT STRATA_WINDOW_MAX_T STREQUAL "12" AND NOT STRATA_WINDOW_MAX_T STREQUAL "16") + message(FATAL_ERROR "STRATA_WINDOW_MAX_T must be auto, 8, 12 or 16 (got '${STRATA_WINDOW_MAX_T}')") +endif() +if(STRATA_ENABLE_HIP OR STRATA_ENABLE_CUDA) + if(STRATA_WINDOW_MAX_T STREQUAL "auto") + if(STRATA_ENABLE_HIP) + set(_strata_window_max_t 16) + else() + set(_strata_window_max_t 8) + endif() + else() + set(_strata_window_max_t ${STRATA_WINDOW_MAX_T}) + endif() + add_compile_definitions(STRATA_VERIFY_MAX_T=${_strata_window_max_t}) + message(STATUS "Strata: verify / batch windows hold up to ${_strata_window_max_t} rows") +endif() # MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K (Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF # projections, STRATA_DENSE_MMQ). On by default since MODEL-UPDATE Phase 1: on CUDA they are their own library # (strata_kq, loaded only for a model with these formats: the engine loads every kernel of its own binary at start, # CUDA_MODULE_LOADING=EAGER, and these took ~3.8 MB of VRAM - 3 IQ3_XXS expert slots on a P100 - from every model); on # HIP a code object loads on first use, so they cost other models nothing there (R9700: the same slots). Used at run # time with STRATA_MMQ_KQ=1 (opt-in: it changes the prompt's rounding against the FP16 path). +option(STRATA_MMQ_TQ_OVERLAY "Gyro trellis MMQ prompt kernels on an upstream llama.cpp: an overlay of its ggml-cuda headers written at configure time (cmake/strata_ggml_tq_overlay.cmake)" ON) option(STRATA_MMQ_KQUANTS "Build the MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K: the experts of Unsloth's K-quant files, and on HIP the dense GGUF projections (STRATA_DENSE_MMQ)" ON) # Q6_K gate/up in the grouped expert kernels (Unsloth's UD-Q6_K_XL, and layer 2 of UD-Q5_K_XL; docs/QUANTS.md). On by # default since MODEL-UPDATE Phase 1: one more instance per grouped kernel in iq_kernels.cu, +19 KB of sm_60 code, @@ -108,6 +163,11 @@ set(_strata_tests_default OFF) if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/bench/micro) set(_strata_tests_default ON) endif() +if(NOT STRATA_CPU_X86) + # arm64 Linux (DGX Spark): much of the suite drives the x86 CPU kernels, which this build does not have. A default, not a + # prohibition: -DSTRATA_BUILD_TESTS=ON still builds what builds (classifying the tests by capability is a follow-up). + set(_strata_tests_default OFF) +endif() option(STRATA_BUILD_TESTS "Build the test suite" ${_strata_tests_default}) option(STRATA_BUILD_CONVERSATION_TESTS "Build standalone conversation cache tests" OFF) option(STRATA_WERROR "Treat compiler warnings as errors" OFF) @@ -162,13 +222,30 @@ elseif(STRATA_ENABLE_CUDA) if(MSVC AND STRATA_EXPERIMENTAL_SM60 AND NOT DEFINED CMAKE_CUDA_RUNTIME_LIBRARY) set(CMAKE_CUDA_RUNTIME_LIBRARY Shared) endif() + # #4023: the default below has to be set BEFORE enable_language(CUDA): since CMake 3.18 that call fills an unset + # CMAKE_CUDA_ARCHITECTURES with nvcc's own default (sm_75 for CUDA 13), so a test after it never saw "undefined" and + # a build with no option was an sm_75 build. -DCMAKE_CUDA_ARCHITECTURES and the CUDAARCHS environment variable win. + set(_strata_cuda_arch_defaulted OFF) + if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES AND NOT DEFINED ENV{CUDAARCHS}) + if(STRATA_BUILD_DSV41) + # #3935: the DeepSeek engine's own release shape (sm_86, sm_89, sm_120 + PTX 120, as packaging/build_dsv41_cuda.sh), so a hand + # build of strata-dsv41 with no architecture runs on an RTX 30, 40 or 50 card; the Qwen engine's default below is unchanged + set(CMAKE_CUDA_ARCHITECTURES "86-real;89-real;120" CACHE STRING "CUDA architectures") + else() + set(CMAKE_CUDA_ARCHITECTURES 120 CACHE STRING "CUDA architectures") + endif() + set(_strata_cuda_arch_defaulted ON) + endif() enable_language(CUDA) # `enable_language(CUDA)` gives the .cu compile rules but NOT the imported targets, so `CUDA::cudart` has to # be brought in explicitly for the host-side tests that call cudaMalloc themselves. find_package(CUDAToolkit REQUIRED) option(STRATA_EXPERIMENTAL_SM60 "community build for GPUs below compute capability 7.5: Pascal sm_60, Volta sm_70 (#236)" OFF) - if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES) - set(CMAKE_CUDA_ARCHITECTURES 120 CACHE STRING "CUDA architectures" FORCE) + if(_strata_cuda_arch_defaulted) + # a recommendation, not a refusal: the release engine is built for 75;86;89;120, a hand build names its card + message(WARNING "Strata: CMAKE_CUDA_ARCHITECTURES was not set, so this build is for ${CMAKE_CUDA_ARCHITECTURES} only (sm_120 = RTX 50). For another " + "card pass it: -DCMAKE_CUDA_ARCHITECTURES=native (the GPUs in this PC), 75 (RTX 20), 86 (RTX 30), " + "89 (RTX 40), or a list like \"86;120\".") endif() foreach(_a IN LISTS CMAKE_CUDA_ARCHITECTURES) string(REGEX REPLACE "-.*$" "" _base "${_a}") # 120-real / 120-virtual are still 120 @@ -190,9 +267,16 @@ elseif(STRATA_ENABLE_CUDA) "CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'. (A Pascal sm_60 or Volta sm_70 build is " "-DSTRATA_EXPERIMENTAL_SM60=ON; upstream does not support it.)") endif() - if(_base LESS 60) + if(_base LESS 52) message(FATAL_ERROR "CMAKE_CUDA_ARCHITECTURES '${CMAKE_CUDA_ARCHITECTURES}': even the experimental build " - "needs compute capability 6.0 (sm_60) or newer") + "needs compute capability 5.2 (sm_52, Maxwell) or newer") + endif() + # Maxwell (sm_52, #3218): one reporter built and ran this on two Quadro M6000 (CUDA 12.x, Qwen3.8-Flash-Next + # IQ1, about 22 t/s). It has no native half-precision arithmetic, so it is slower per byte than Pascal; only + # this opt-in build gets the floor. Warn, do not refuse. + if(_base LESS 60) + message(WARNING "Building for sm_${_base} (Maxwell): community-tested on one reporter's Quadro M6000 only, " + "no native half-precision arithmetic, CUDA 12.x toolkit required (docs/OLDER_GPUS.md).") endif() # #220 / #224: RTX 50 engines built with CUDA 12.8 crashed in the prompt path on Linux (13.0 and newer did not) if(_base GREATER_EQUAL 120 AND CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 13.0) @@ -254,6 +338,9 @@ target_link_libraries(strata-dequant PRIVATE strata_artifact) # this file is now nothing but the CLI entry point, and its inherited guard spells that as a "selftest" target_compile_definitions(strata-dequant PRIVATE STRATA_DEQUANT_SELFTEST) if(STRATA_BUILD_TESTS) + add_executable(batch_telemetry_test src/core/batch_telemetry_test.cpp) + target_include_directories(batch_telemetry_test PRIVATE include) + add_test(NAME batch_telemetry_test COMMAND batch_telemetry_test) add_executable(logit_bias_test src/core/logit_bias_test.cpp) target_include_directories(logit_bias_test PRIVATE include) add_test(NAME logit_bias_test COMMAND logit_bias_test) @@ -289,15 +376,44 @@ if(STRATA_BUILD_TESTS) target_include_directories(split_rules_test PRIVATE include) add_test(NAME split_rules_test COMMAND split_rules_test) + # #3797: the out-of-memory report at start (per card free/total, the largest other programs): the text is a pure + # function; the driver query (NVML, loaded at run time) is only checked to be safe to call. No GPU needed. + add_executable(gpu_report_test tests/program/gpu_report_test.cpp) + target_include_directories(gpu_report_test PRIVATE include) + target_link_libraries(gpu_report_test PRIVATE ${CMAKE_DL_LIBS}) + add_test(NAME gpu_report_test COMMAND gpu_report_test) + + # #3702: the later-stage reserve of the layer split search (header-only arithmetic, pinned against the old expression) + add_executable(stage_reserve_test tests/program/stage_reserve_test.cpp) + target_include_directories(stage_reserve_test PRIVATE include) + add_test(NAME stage_reserve_test COMMAND stage_reserve_test) + + # the prompt planner's host-memory model (#2824): header-only, no GPU + add_executable(prefill_plan_test tests/program/prefill_plan_test.cpp) + target_include_directories(prefill_plan_test PRIVATE include) + add_test(NAME prefill_plan_test COMMAND prefill_plan_test) + # the default CPU prefill share is not armed when every expert is resident (#1595): header-only rule, no GPU add_executable(share_rules_test tests/prefill/share_rules_test.cpp) target_include_directories(share_rules_test PRIVATE include) add_test(NAME share_rules_test COMMAND share_rules_test) + # STRATA_PREFILL_ROUTED_STREAM: the prompt stream's issuer walk and route gate, on a simulated link and consumer + # (header-only, no GPU) + add_executable(routed_stream_test tests/prefill/routed_stream_test.cpp) + target_include_directories(routed_stream_test PRIVATE include) + target_link_libraries(routed_stream_test PRIVATE Threads::Threads) + add_test(NAME routed_stream_test COMMAND routed_stream_test) + # the Windows HIP auto prefill chunk cap (#1630) and the commit-limit verdict (#1607): header-only, no GPU add_executable(host_limits_test tests/platform/host_limits_test.cpp) target_include_directories(host_limits_test PRIVATE include) add_test(NAME host_limits_test COMMAND host_limits_test) + # #4733: an engine started at Low I/O priority goes back to Normal (Windows; else skips) + add_executable(io_priority_test tests/platform/io_priority_test.cpp src/platform/io_priority.cpp) + target_include_directories(io_priority_test PRIVATE include) + add_test(NAME io_priority_test COMMAND io_priority_test) + set_tests_properties(io_priority_test PROPERTIES SKIP_RETURN_CODE 77) endif() # ---- strata_plan ---------------------------------------------------------- @@ -313,9 +429,11 @@ target_link_libraries(strata-plan PRIVATE strata_plan) # ---- strata_core (GPU runtime) --------------------------------------------- # Only built when a GPU backend is on, so the Phase 1 targets keep working without a toolkit. if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) - add_library(strata_core STATIC src/core/device.cu src/core/pinned.cu src/platform/memory.cpp src/core/graph.cpp src/core/weights.cpp + add_library(strata_core STATIC src/core/device.cu src/core/pinned.cu src/platform/memory.cpp src/platform/io_priority.cpp src/core/graph.cpp src/core/weights.cpp src/core/layout.cpp) target_include_directories(strata_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + # the DFlash2 drafter (src/core/dflash2.cpp, src/kernels/cuda/dflash2.cu) exists in the CUDA and HIP builds; the Metal and SYCL builds compile without it + target_compile_definitions(strata_core PUBLIC STRATA_HAVE_DFLASH2=1) if(STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) # the runtime device check (src/core/device.cu) admits the cards this build was made for (#236) target_compile_definitions(strata_core PRIVATE STRATA_EXPERIMENTAL_SM60=1) @@ -356,6 +474,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # reference is the whole point - a kernel checked against another copy of itself proves nothing. add_library(strata_kernels STATIC src/kernels/cuda/dequant_s2.cu src/kernels/cuda/s2_gemv.cu src/kernels/cuda/s_gemv.cu + src/kernels/cuda/s_gemv_pair.cu src/kernels/cuda/s2_gemv_quads.cu src/kernels/cuda/s2_gemv_fast.cu src/kernels/cuda/router_top10.cu @@ -396,7 +515,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/fused_gdn.cu src/kernels/cuda/dequant_bf16.cu src/kernels/cuda/qsa_select.cu + src/kernels/cuda/qsa_pattn.cu src/kernels/cuda/verify_kernels.cu + src/kernels/cuda/dflash2.cu src/kernels/cuda/iq_kernels.cu src/kernels/ngram.cpp src/ngram/ple_reader.cpp @@ -424,6 +545,36 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart) endif() + # PR #3943: STRATA_PATTN_SM60's score and value kernels against the decode kernels' output (the Daily's chunk kernel and + # the merge), bitwise, on random int8 K/V (GPU, synthetic, no model). Only in the experimental sm_60 build; it skips + # (77) on a build without the kernels. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_pattn_parity src/kernels/qsa_pattn_parity.cpp) + target_include_directories(qsa_pattn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_pattn_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_pattn_parity COMMAND qsa_pattn_parity) + set_tests_properties(qsa_pattn_parity PROPERTIES SKIP_RETURN_CODE 77) + endif() + # PR #3820: STRATA_SELECT_LONG's multi-CTA top-k and shuffle-free decode scorer against qsa_block_topk and + # qsa_block_scores, bitwise, on random scores (GPU, synthetic, no model). The switches force the new kernels on any + # card; the "n3" case fixes three CTAs a query. Only in the experimental sm_60 build (skips with 77 otherwise). + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_select_long_parity src/kernels/qsa_select_long_parity.cpp) + target_include_directories(qsa_select_long_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_select_long_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_select_long_parity COMMAND qsa_select_long_parity) + add_test(NAME qsa_select_long_parity_n3 COMMAND qsa_select_long_parity) + set_tests_properties(qsa_select_long_parity qsa_select_long_parity_n3 PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(qsa_select_long_parity PROPERTIES ENVIRONMENT "STRATA_SCORES_DX=1;STRATA_TOPK_MULTI=1") + set_tests_properties(qsa_select_long_parity_n3 PROPERTIES ENVIRONMENT "STRATA_SCORES_DX=1;STRATA_TOPK_MULTI=1;STRATA_TOPK_MULTI_N=3") + endif() + # PR #600: the Volta (sm_70) prompt attention's latency pipeline against the FP32 kernel it replaces. Only in the + # experimental sm_60/sm_70 build, where prompt_attn_v70_kernel is compiled in. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_prompt_attn_sm70_bench bench/qsa_prompt_attn_sm70_bench.cpp) + target_include_directories(qsa_prompt_attn_sm70_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_prompt_attn_sm70_bench PRIVATE strata_kernels CUDA::cudart) + endif() # #512: the top-k's active-block bound (Turing's dispatch, forced on any card by STRATA_TOPK_ACTIVE_ANY) against # the capacity rule, selected ids bitwise if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) @@ -551,9 +702,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # about arithmetic, and this one knows the ORDER the arithmetic happens in. add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp src/core/remote_expert_opt.cu - src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp + src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp src/core/dflash2.cpp src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp - src/core/arch_defaults.cpp src/core/vmm.cpp src/core/conversation_file.cpp) + src/core/arch_defaults.cpp src/core/nv_defaults.cpp src/core/vmm.cpp src/core/conversation_file.cpp) target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target}) if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) @@ -655,6 +806,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(conversation_snapshot_test PRIVATE strata_engine) add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test) set_tests_properties(conversation_snapshot_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # the same test with a GDN state over 1 MiB and the opt-in background checkpoint copy (STRATA_CKPT_ASYNC=1), alone and with + # recent states kept in VRAM (STRATA_CKPT_VRAM_SLOTS): every checkpoint, capture and restore must give the same bytes + add_test(NAME conversation_snapshot_test_ckpt_async COMMAND conversation_snapshot_test) + set_tests_properties(conversation_snapshot_test_ckpt_async PROPERTIES + ENVIRONMENT "STRATA_TEST_BIG_GDN=1;STRATA_CKPT_ASYNC=1" SKIP_RETURN_CODE 77 TIMEOUT 300) + add_test(NAME conversation_snapshot_test_ckpt_vram_slots COMMAND conversation_snapshot_test) + set_tests_properties(conversation_snapshot_test_ckpt_vram_slots PROPERTIES + ENVIRONMENT "STRATA_TEST_BIG_GDN=1;STRATA_CKPT_ASYNC=1;STRATA_CKPT_VRAM_SLOTS=3" SKIP_RETURN_CODE 77 TIMEOUT 300) add_executable(conversation_validation_test src/core/conversation_validation_test.cpp) target_link_libraries(conversation_validation_test PRIVATE strata_engine) add_test(NAME conversation_validation_test COMMAND conversation_validation_test) @@ -683,6 +842,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) endif() target_include_directories(strata_prefill PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) target_link_libraries(strata_prefill PUBLIC strata_engine ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) + if(STRATA_ENABLE_CUDA) + # v100/gdn-chunk: the chunked Volta GDN prompt recurrence. The dispatch (src/prefill/kernels.cu) is + # Volta-only (cc 7.0) and gated on STRATA_EXPERIMENTAL_SM60; the path itself stays opt-in (STRATA_GDN_CHUNK). + target_sources(strata_prefill PRIVATE src/prefill/gdn_chunk.cu) + endif() if(STRATA_ENABLE_HIP AND STRATA_HIPBLASLT_AVAILABLE) target_compile_definitions(strata_prefill PRIVATE STRATA_HIPBLASLT_AVAILABLE=1) target_link_libraries(strata_prefill PRIVATE roc::hipblaslt) @@ -699,9 +863,44 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(tune_rocblas PRIVATE hip::host roc::rocblas) endif() + # DFlash2 drafter tools (not built by default: cmake --build --target dflash2_parity dflash2_gemm_bench dflash2_attn_bench): the drafter against + # the torch port on a synthetic case (needs the pack and a case file, tools/dflash2/mk_parity_case.py), and the timing of its Q8 GEMM and attention + add_executable(dflash2_parity EXCLUDE_FROM_ALL src/core/dflash2_parity.cpp) + target_include_directories(dflash2_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_parity PRIVATE strata_engine strata_kernels ${_strata_gpu_runtime_target}) + add_executable(dflash2_q4_parity EXCLUDE_FROM_ALL src/core/dflash2_q4_parity.cpp) + target_include_directories(dflash2_q4_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_q4_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_executable(dflash2_ring_test EXCLUDE_FROM_ALL src/core/dflash2_ring_test.cpp) # the drafter's ring log and rebuild against an uninterrupted update sequence + target_include_directories(dflash2_ring_test PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_ring_test PRIVATE strata_engine strata_kernels ${_strata_gpu_runtime_target}) + add_executable(dflash2_gemm_bench EXCLUDE_FROM_ALL src/core/dflash2_gemm_bench.cpp) + target_include_directories(dflash2_gemm_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_gemm_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_executable(dflash2_launch_bench EXCLUDE_FROM_ALL src/core/dflash2_launch_bench.cu) + target_include_directories(dflash2_launch_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_launch_bench PRIVATE ${_strata_gpu_runtime_target}) + add_executable(dflash2_bw_bench EXCLUDE_FROM_ALL src/core/dflash2_bw_bench.cu) + target_include_directories(dflash2_bw_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_bw_bench PRIVATE ${_strata_gpu_runtime_target}) + add_executable(dflash2_small_bench EXCLUDE_FROM_ALL src/core/dflash2_small_bench.cpp) + target_include_directories(dflash2_small_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_small_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_executable(dflash2_attn_bench EXCLUDE_FROM_ALL src/core/dflash2_attn_bench.cpp) + target_include_directories(dflash2_attn_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_attn_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_executable(strata src/program/generate.cpp) + strata_utf8_manifest(strata) target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target}) + if(WIN32 AND STRATA_ENABLE_HIP) + # 0.2.1.2: the ROCm math libraries live in \rocm\bin, which is on PATH only when the launcher starts the engine; load them on first + # use (main() adds that folder to the DLL search first) so `strata.exe --version` works from the package folder. amdhip64_7.dll and the + # C++ runtime sit beside the exe (tools/hip/package_windows.py) and stay normal imports. + target_link_libraries(strata PRIVATE delayimp) + target_link_options(strata PRIVATE "LINKER:/DELAYLOAD:hipblas.dll" "LINKER:/DELAYLOAD:libhipblaslt.dll" "LINKER:/DELAYLOAD:rocblas.dll") + endif() # NEW-MODELS-PLAN.md T1: Qwen3.6-35B-A3B's reference path (one GPU, the model resident, plain kernels), checked # against llama.cpp by tools/qwen35/; the engine itself does not run the family yet @@ -710,7 +909,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(strata-q36ref PRIVATE strata_kernels strata_warnings ${_strata_gpu_runtime_target}) # the engine path for the same family (serve protocol, prompt chunks, decode graph): src/qwen35/q36_engine.cu, a # library that `strata` switches to for a qwen35moe model (the family switch at the top of its main) and that - # strata-q36 wraps on its own + # strata-q36 wraps on its own. Not on gfx906 (#3172, #3271): it calls cuBLAS entry points the wave64 compat layer does + # not map (cublasSgemm, cublasGemmStridedBatchedEx) and its kernels assume 32-lane warps; main() guards every use with + # STRATA_HAVE_QWEN35, so a gfx906 build links and runs the Qwen3.8 family, and `strata --families` says so + if(NOT STRATA_HIP_GFX906) add_library(strata_qwen35 STATIC src/qwen35/q36_engine.cu) target_include_directories(strata_qwen35 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(strata_qwen35 PRIVATE strata_prefill strata_kernels strata_warnings ${_strata_gpu_runtime_target}) @@ -720,9 +922,176 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_compile_definitions(strata_qwen35 PRIVATE STRATA_Q36_CPU_POOL=1) endif() add_executable(strata-q36 src/qwen35/q36_main.cpp) + strata_utf8_manifest(strata-q36) target_link_libraries(strata-q36 PRIVATE strata_qwen35 ${_strata_gpu_runtime_target}) target_link_libraries(strata PRIVATE strata_qwen35) target_compile_definitions(strata PRIVATE STRATA_HAVE_QWEN35=1) + endif() + + # DeepSeek-V4.1-Flash: the third engine path (src/dsv41, from Project Maya's maya-ds4, MIT, third_party/project-maya). + # Its own executable for now (strata-dsv41); a family switch in `strata` comes after first light. OFF by default: it + # changes no existing target (the vendored kernels live in strata::dsv41k, so no symbol is shared with strata_kernels). + option(STRATA_BUILD_DSV41 "Build the DeepSeek-V4.1 engine path (strata-dsv41)" OFF) + if(STRATA_BUILD_DSV41 AND NOT STRATA_HIP_GFX906) + add_library(strata_dsv41_kernels STATIC src/dsv41/vendor/exl3.cu src/dsv41/vendor/sampler.cu src/dsv41/vendor/moe_win.cu + src/dsv41/vendor/exl3_cpu.cpp) + if(NOT STRATA_ENABLE_HIP) # (the pre-sm_80 NVIDIA decode kernels exl3.cu dispatches to) + target_sources(strata_dsv41_kernels PRIVATE src/dsv41/vendor/exl3_legacy.cu) + endif() + target_include_directories(strata_dsv41_kernels PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + target_link_libraries(strata_dsv41_kernels PUBLIC ${_strata_gpu_runtime_target}) + add_executable(strata-dsv41 src/dsv41/ds4_main.cpp src/dsv41/ds4_model.cu src/dsv41/ds4_kernels.cu src/dsv41/ds4_vision.cu + src/dsv41/ds4_gguf.cu src/dsv41/ds4_gguf_cpu.cpp src/dsv41/ds4_iq.cu src/dsv41/ds4_iq_cpu.cpp + src/dsv41/ds4_tq.cu src/dsv41/ds4_tq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp src/dsv41/ds4_packinfo.cpp src/platform/io_priority.cpp) + # the commit the binary was built from, readable with --version (set -DSTRATA_BUILD_ID=... for a tree without .git) + if(NOT STRATA_BUILD_ID AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/BUILD_ID) # (a git archive has no .git: the packer writes the commit here) + file(STRINGS ${CMAKE_CURRENT_SOURCE_DIR}/BUILD_ID STRATA_BUILD_ID LIMIT_COUNT 1) + endif() + if(NOT STRATA_BUILD_ID) + execute_process(COMMAND git -C ${CMAKE_CURRENT_SOURCE_DIR} rev-parse --short=9 HEAD OUTPUT_VARIABLE STRATA_BUILD_ID + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + endif() + if(NOT STRATA_BUILD_ID) + set(STRATA_BUILD_ID unknown) + endif() + set_source_files_properties(src/dsv41/ds4_main.cpp PROPERTIES COMPILE_DEFINITIONS "DS4_BUILD_ID=\"${STRATA_BUILD_ID}\"") + target_include_directories(strata-dsv41 PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill) + # strata_prefill: the RDNA3 WMMA dense GEMM (src/prefill/wmma_gemm.cu), which gemm() prefers over hipBLAS on gfx11 (measured + # 4.97 -> 20-40 TFLOPS on this part: the chunked prompt's dense GEMM is 11.1 s of a 4K prompt at the library's rate) + target_link_libraries(strata-dsv41 PRIVATE strata_prefill strata_dsv41_kernels ${_strata_gpu_runtime_target} ${_strata_gpu_blas_target}) + find_package(Threads REQUIRED) + target_link_libraries(strata-dsv41 PRIVATE Threads::Threads) + if(WIN32 AND STRATA_ENABLE_HIP) # cudaMemGetInfo is the DXGI-budgeted hip_compat::mem_get_info (src/core/device.cu): on a Strix Halo the + # carve-out is not all the GPU may use, and the engine sizes its expert tiers by what the budget says is free + target_link_libraries(strata-dsv41 PRIVATE strata_core) + endif() + if(STRATA_NATIVE_EXPERTS) # Strata's CPU trellis kernels (tq_cpu.hpp) for the trellis experts on the CPU lane + target_link_libraries(strata-dsv41 PRIVATE strata_kernels_cpu) + target_compile_definitions(strata-dsv41 PRIVATE STRATA_DSV41_TQ_CPU=1) + endif() + if(STRATA_NATIVE_EXPERTS) + # the CPU lane's ggml-type rows: ggml-cpu's dots against Strata's AVX2 i-quant rows (bits and GB/s); no GPU, no model + add_executable(ds4_gg_bench tests/dsv41/gg_dot_bench.cpp src/dsv41/ds4_gg_cpu.cpp) + target_include_directories(ds4_gg_bench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41 + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) + target_link_libraries(ds4_gg_bench PRIVATE strata_kernels_cpu Threads::Threads) + target_compile_definitions(ds4_gg_bench PRIVATE STRATA_DSV41_TQ_CPU=1) + # the PCIe lane's cost model on this CPU (Project Maya #312's tests/ds4_lane_bench): no GPU, no model + add_executable(ds4_lane_bench tests/dsv41/ds4_lane_bench.cpp src/dsv41/ds4_gguf_cpu.cpp src/dsv41/ds4_iq_cpu.cpp + src/dsv41/ds4_tq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp) + target_include_directories(ds4_lane_bench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41 + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) + target_link_libraries(ds4_lane_bench PRIVATE strata_dsv41_kernels strata_kernels_cpu Threads::Threads) + target_compile_definitions(ds4_lane_bench PRIVATE STRATA_DSV41_TQ_CPU=1) + endif() + # the GGUF kernels against a double-precision reference, the PCIe lane's streamed experts against the VRAM ones' bit for + # bit (--lane), and the packed KV caches against the BF16 rows (needs a GPU, no model; built by name) + add_executable(ds4_gguf_test EXCLUDE_FROM_ALL tests/dsv41/ds4_gguf_test.cu src/dsv41/ds4_gguf.cu src/dsv41/ds4_gguf_cpu.cpp + src/dsv41/ds4_iq.cu src/dsv41/ds4_iq_cpu.cpp src/dsv41/ds4_kernels.cu src/dsv41/ds4_tq.cu + src/dsv41/ds4_tq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp) + target_include_directories(ds4_gguf_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill) + target_link_libraries(ds4_gguf_test PRIVATE strata_prefill strata_dsv41_kernels ${_strata_gpu_runtime_target} Threads::Threads) + if(STRATA_NATIVE_EXPERTS) + target_link_libraries(ds4_gguf_test PRIVATE strata_kernels_cpu) + target_compile_definitions(ds4_gguf_test PRIVATE STRATA_DSV41_TQ_CPU=1) + endif() + # the router on a non-finite gate input (valid, distinct picks; the same picks as the host's top-k when finite) and its + # launch times; needs a GPU, no model; built by name + add_executable(ds4_route_guard_test EXCLUDE_FROM_ALL tests/dsv41/ds4_route_guard_test.cu src/dsv41/ds4_kernels.cu) + target_include_directories(ds4_route_guard_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + target_link_libraries(ds4_route_guard_test PRIVATE strata_dsv41_kernels ${_strata_gpu_runtime_target} Threads::Threads) + if(STRATA_NATIVE_EXPERTS) + # the trellis experts (device kernels ds4_tq.cu, CPU lane ds4_tq_cpu.cpp) against a double reference; needs a GPU, no model + # both test .cpp files launch kernels, so they compile as HIP on the AMD backend and as CUDA on the NVIDIA one + if(STRATA_ENABLE_HIP) + set(_ds4_test_lang HIP) + elseif(STRATA_ENABLE_CUDA) + set(_ds4_test_lang CUDA) + else() + set(_ds4_test_lang CXX) + endif() + set_source_files_properties(tests/dsv41/tq_expert_test.cpp PROPERTIES LANGUAGE ${_ds4_test_lang}) + add_executable(ds4_tq_test tests/dsv41/tq_expert_test.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_iq.cu src/dsv41/ds4_tq_cpu.cpp + src/dsv41/ds4_iq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp tools/trellis/tqenc.cpp) + target_include_directories(ds4_tq_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) + target_link_libraries(ds4_tq_test PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) + target_compile_definitions(ds4_tq_test PRIVATE STRATA_DSV41_TQ_CPU=1) + # the same with the plain-FMA tile instead of the gfx12 WMMA one (what CUDA and gfx11 builds run) + add_executable(ds4_tq_test_portable tests/dsv41/tq_expert_test.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_iq.cu src/dsv41/ds4_tq_cpu.cpp + src/dsv41/ds4_iq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp tools/trellis/tqenc.cpp) + target_include_directories(ds4_tq_test_portable PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) + target_link_libraries(ds4_tq_test_portable PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) + target_compile_definitions(ds4_tq_test_portable PRIVATE STRATA_DSV41_TQ_CPU=1 DS4_TQ_PORTABLE=1) + if(STRATA_ENABLE_HIP) + target_compile_options(ds4_tq_test_portable PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") + endif() + if(STRATA_ENABLE_HIP) + target_compile_options(ds4_tq_test PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") + endif() + # the i-quant experts (ds4_iq.cu) against ggml's own decode of the same blocks + a double reference, device and CPU + # lane, for every type the device takes: the gate a new type (IQ2_XS ..) has to pass before the engine uses it + set_source_files_properties(tests/dsv41/iq_expert_test.cpp PROPERTIES LANGUAGE ${_ds4_test_lang}) + add_executable(ds4_iq_test tests/dsv41/iq_expert_test.cpp src/dsv41/ds4_iq.cu src/dsv41/ds4_iq_cpu.cpp + src/dsv41/ds4_gg_cpu.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_tq_cpu.cpp) + target_include_directories(ds4_iq_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) + target_link_libraries(ds4_iq_test PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) + target_compile_definitions(ds4_iq_test PRIVATE STRATA_DSV41_TQ_CPU=1) + if(STRATA_ENABLE_HIP) + target_compile_options(ds4_iq_test PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") + endif() + # the dense weights (ds4_iq.cu dequant_rows / mv / f16_rows, ds4_gguf.cu rows / mv, the chunk GEMM) against a CPU reference for every + # dense type and shape, no ggml, no model: tests/dsv41/dq_dense_test.cpp (run_dq_test.sh runs it a process a type and kernel) + set_source_files_properties(tests/dsv41/dq_dense_test.cpp PROPERTIES LANGUAGE ${_ds4_test_lang}) + add_executable(ds4_dq_test tests/dsv41/dq_dense_test.cpp src/dsv41/ds4_iq.cu src/dsv41/ds4_tq.cu src/dsv41/ds4_gguf.cu) + target_include_directories(ds4_dq_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_link_libraries(ds4_dq_test PRIVATE strata_prefill ${_strata_gpu_runtime_target} ${_strata_gpu_blas_target} Threads::Threads) + target_compile_definitions(ds4_dq_test PRIVATE DQ_TEST_GGUF=1 DQ_TEST_GEMM=1) + if(STRATA_ENABLE_HIP) + target_compile_options(ds4_dq_test PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") + endif() + # the kept conversations' .meta file and prefix matching (ds4_slotmeta.hpp): no GPU, no model + add_executable(ds4_slot_test tests/dsv41/slot_test.cpp) + target_include_directories(ds4_slot_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_slot_test PRIVATE cxx_std_17) + # restore points (ds4_marks.hpp, from Project Maya #639): which point a prompt goes back to, which ones a read keeps + add_executable(ds4_marks_test tests/dsv41/marks_test.cpp) + target_include_directories(ds4_marks_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_marks_test PRIVATE cxx_std_17) + # the staging ring's slots by the measured host link (ds4_ring_link.hpp, from Project Maya #609) + add_executable(ds4_ring_link_test tests/dsv41/ring_link_test.cpp) + target_include_directories(ds4_ring_link_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_ring_link_test PRIVATE cxx_std_17) + # the serve loop's event queue (ds4_evt.hpp, from Project Maya #587) + add_executable(ds4_evt_test tests/dsv41/evt_test.cpp) + target_include_directories(ds4_evt_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_evt_test PRIVATE cxx_std_17) + find_package(Threads) + if(Threads_FOUND) + target_link_libraries(ds4_evt_test PRIVATE Threads::Threads) + endif() + add_executable(ds4_experts_rule_test tests/dsv41/experts_rule_test.cpp) + target_include_directories(ds4_experts_rule_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_experts_rule_test PRIVATE cxx_std_17) + # the timing pick's per-size-class flow correction (ds4_path_policy.hpp, from Project Maya #612) + add_executable(ds4_path_policy_test tests/dsv41/path_policy_test.cpp) + target_include_directories(ds4_path_policy_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_path_policy_test PRIVATE cxx_std_17) + add_executable(ds4_pick_rule_test tests/dsv41/pick_rule_test.cpp) + target_include_directories(ds4_pick_rule_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_pick_rule_test PRIVATE cxx_std_17) + endif() + if(STRATA_ENABLE_HIP) + foreach(_t strata_dsv41_kernels strata-dsv41) + target_compile_options(${_t} PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") + endforeach() + endif() + endif() if(STRATA_ENABLE_HIP) enable_testing() @@ -739,6 +1108,20 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(hip_q2_zero PRIVATE strata_kernels strata_hip_runtime) add_test(NAME hip_q2_zero COMMAND hip_q2_zero) list(APPEND _strata_hip_tests hip_q2_zero) + # the QSA layer's fused norm + rope (rms_rope_rows, STRATA_QSA_FUSE_NR) against split_q + rms_rows + rope, bit for bit over the + # whole output; and the gfx11 prompt GEMMs' full-output coverage (every element written, sampled rows against FP64). + # GPU, synthetic, no model; exit 77 without a gfx11 device. + add_executable(hip_qsa_nr_parity src/prefill/qsa_nr_parity.cu) + target_link_libraries(hip_qsa_nr_parity PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_qsa_nr_parity COMMAND hip_qsa_nr_parity) + set_tests_properties(hip_qsa_nr_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + list(APPEND _strata_hip_tests hip_qsa_nr_parity) + add_executable(hip_pf_cover_test src/prefill/pf_cover_test.cu) + target_include_directories(hip_pf_cover_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill) + target_link_libraries(hip_pf_cover_test PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_pf_cover_test COMMAND hip_pf_cover_test) + set_tests_properties(hip_pf_cover_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 900) + list(APPEND _strata_hip_tests hip_pf_cover_test) add_executable(hip_expert_cache_staging tests/hip/expert_cache_staging.cpp) target_link_libraries(hip_expert_cache_staging PRIVATE strata_engine) add_test(NAME hip_expert_cache_staging COMMAND hip_expert_cache_staging) @@ -787,6 +1170,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME hip_gdn_chunked_off COMMAND hip_gdn_chunked --off) add_test(NAME hip_gdn_chunked_default COMMAND hip_gdn_chunked --default) list(APPEND _strata_hip_tests hip_gdn_chunked hip_gdn_chunked_off hip_gdn_chunked_default) + # GDN prompt stage bench (gates + conv + recurrence, per-piece times and output/state hashes at 4K/16K/32K); a measurement + # tool, run by hand with the STRATA_GDN_* knobs under test - no add_test + add_executable(hip_gdn_stage_bench tests/hip/gdn_stage_bench.cpp) + target_link_libraries(hip_gdn_stage_bench PRIVATE strata_prefill strata_hip_runtime) # #313: the RDNA3 / RDNA3.5 WMMA dense GEMMs (opt-in STRATA_WMMA_GEMM=1) against a reference add_executable(hip_prefill_wmma_gemm_parity tests/hip/prefill_wmma_gemm_parity.cpp) target_include_directories(hip_prefill_wmma_gemm_parity PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") @@ -800,12 +1187,18 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME hip_prefill_hcd_exact_parity COMMAND hip_prefill_hcd_exact_parity) set_tests_properties(hip_prefill_hcd_exact_parity PROPERTIES SKIP_RETURN_CODE 77) list(APPEND _strata_hip_tests hip_prefill_hcd_exact_parity) + # the HC write-back kernel timed at the prompt path's shapes with an output checksum (not a ctest; STRATA_GRW_V picks a variant) + add_executable(hip_prefill_gr_write_bench tests/hip/prefill_gr_write_bench.cpp) + target_link_libraries(hip_prefill_gr_write_bench PRIVATE strata_prefill strata_hip_runtime) # S6: the AMD fast router against the portable kernel, bitwise add_executable(hip_router_fast tests/hip/router_fast.cpp) target_link_libraries(hip_router_fast PRIVATE strata_kernels strata_hip_runtime) add_test(NAME hip_router_fast COMMAND hip_router_fast) list(APPEND _strata_hip_tests hip_router_fast) # S6: the RDNA4 matrix-core prompt attention (STRATA_HIP_WMMA) against the FP32 kernel and FP64; skips off gfx12 + # the prompt attention on a recorded selection (STRATA_QSA_DUMP), for A/B of kernel variants (STRATA_QSA_UNION=1) + add_executable(hip_pa_bench tests/cuda/pa_bench.cpp) + target_link_libraries(hip_pa_bench PRIVATE strata_kernels strata_hip_runtime) add_executable(hip_prompt_attn_wmma src/kernels/qsa_prompt_attn_parity.cpp) target_link_libraries(hip_prompt_attn_wmma PRIVATE strata_kernels strata_hip_runtime) add_test(NAME hip_prompt_attn_wmma COMMAND hip_prompt_attn_wmma 32768 2048 3) @@ -919,6 +1312,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(mmvq_il_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(mmvq_il_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME mmvq_il_parity COMMAND mmvq_il_parity) + # sm_89's opt-in tables (#3453, STRATA_MMVQ_IL_89=1): the table check only (no case matches MMVQ_IL_ONLY) + add_test(NAME mmvq_il_parity_89table COMMAND mmvq_il_parity) + set_tests_properties(mmvq_il_parity_89table PROPERTIES ENVIRONMENT "STRATA_MMVQ_IL_89=1;MMVQ_IL_ONLY=no-such-case") + # the opt-in STRATA_MMVQ_IL_PF kernels (hoisted group loads, exact integer forms): every variant bit-checked against + # native_mmvq for every type, shape, T and rows choice + add_test(NAME mmvq_il_parity_pf COMMAND mmvq_il_parity --pf 0,2,3,4,5,6) + set_tests_properties(mmvq_il_parity_pf PROPERTIES TIMEOUT 900) # the wide dequant kernels (a thread per 8 values; sm_61's default), bitwise vs the per-group ones (GPU, synthetic, # no model; --bench adds old/new timings) add_executable(dequant_wide_parity src/kernels/dequant_wide_parity.cpp) @@ -943,6 +1343,21 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(iq_multi_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(iq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME iq_multi_parity COMMAND iq_multi_parity) + # the Gyro trellis decode kernels (TQ2_T / TQK6 / TQK7) on synthetic blocks: decode-once vs per-column bitwise, output + # checksums to compare two builds byte for byte, --bench for timings (GPU, no model) + add_executable(tq_pascal_bench src/kernels/tq_pascal_bench.cpp) + target_include_directories(tq_pascal_bench PRIVATE ${_strata_gpu_include_directories} ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) + target_link_libraries(tq_pascal_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME tq_pascal_bench COMMAND tq_pascal_bench) + set_tests_properties(iq_multi_parity PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1") # the Q4_K / Q5_K / Q8_0 Split path against the old kernels + # the same Split path on the other routes it can meet: the generic multi kernels (no V2K) and the fused gate/up + SwiGLU kernel, and the sub-16-row + # gate/up route switched off (a K-quant row has 160 dots, not the 80 the sub-16 rows assume: STRATA_KQ_SPLIT=1 must stay bitwise on all of them) + add_test(NAME iq_multi_parity_kq_nov2k COMMAND iq_multi_parity) + set_tests_properties(iq_multi_parity_kq_nov2k PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1;STRATA_EXPERT_V2K=0") + add_test(NAME iq_multi_parity_kq_swiglu COMMAND iq_multi_parity) + set_tests_properties(iq_multi_parity_kq_swiglu PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1;STRATA_GU_SWIGLU=1") + add_test(NAME iq_multi_parity_kq_nosub16 COMMAND iq_multi_parity) + set_tests_properties(iq_multi_parity_kq_nosub16 PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1;STRATA_NO_SUB16_GU=1") # the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise (GPU, # synthetic, no model; --bench adds timings). NVIDIA only: cp.async and the CUDA occupancy API (not on gfx906) if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) @@ -959,11 +1374,36 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu) target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target}) add_test(NAME gdn_rec_parity COMMAND gdn_rec_parity) + # STRATA_GDN_TC=1: the tensor-core helpers of the scan, each on one warp against a double-precision reference. Any sm_80+ + # card runs them; the scan itself needs 122 KB of shared memory a block (sm_80, sm_90), where gdn_rec_parity prints + # "not on this card" for the tc variant + add_test(NAME gdn_rec_parity_selftest_frag COMMAND gdn_rec_parity --selftest-frag) + set_tests_properties(gdn_rec_parity_selftest_frag PROPERTIES SKIP_RETURN_CODE 77) + # the production-linked GDN parity / benchmark harness (no kernel copies: it calls gdn_gates, gdn_conv and + # gdn_recurrence of strata_prefill through the GdnProbe of include/strata/prefill/gdn_probe.hpp, against an FP64 + # oracle from tests/gdn/gdn_fixture.hpp). Usage: docs/GDN_CONTRACT.md. The smoke test is small and CPU-cheap. + execute_process(COMMAND git -C ${CMAKE_CURRENT_SOURCE_DIR} rev-parse --short=9 HEAD OUTPUT_VARIABLE _gdn_sha + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + if(NOT _gdn_sha) + set(_gdn_sha unknown) + endif() + add_executable(gdn_harness src/prefill/gdn_harness.cu) + target_include_directories(gdn_harness PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests/gdn) + target_compile_definitions(gdn_harness PRIVATE GDN_HARNESS_SHA="${_gdn_sha}") + target_link_libraries(gdn_harness PRIVATE strata_prefill) + add_test(NAME gdn_harness_smoke COMMAND gdn_harness --T 400 --chunk 160 --cuts 37 --paths auto,keyhead,pipe --ref-heads 0,17) + set_tests_properties(gdn_harness_smoke PROPERTIES TIMEOUT 300) # the prompt path's BF16 products against cuBLAS's own BF16 GEMM, within fp32 rounding (sm_7x runs them on the # FP16 tensor cores; GPU, synthetic, no model; --bench adds timings) add_executable(gemm_bf16_parity src/prefill/gemm_bf16_parity.cu) target_link_libraries(gemm_bf16_parity PRIVATE strata_prefill ) add_test(NAME gemm_bf16_parity COMMAND gemm_bf16_parity) + # STRATA_DEQUANT_SIDE: Gemm::native with the dense dequant on a side stream (two scratches) against the serial form, + # bitwise (GPU, synthetic, no model; 77 without a device) + add_executable(gemm_dequant_side_parity src/prefill/gemm_dequant_side_parity.cu) + target_link_libraries(gemm_dequant_side_parity PRIVATE strata_prefill ) + add_test(NAME gemm_dequant_side_parity COMMAND gemm_dequant_side_parity) + set_tests_properties(gemm_dequant_side_parity PROPERTIES SKIP_RETURN_CODE 77) # Pascal, opt-in STRATA_DENSE_F32=1: the dense projections' FP16 GEMMs as cublasSgemm on FP32 copies, bitwise vs # the cuBLAS FP16 call over a sweep of chunk sizes (GPU, synthetic, no model; --full sweeps every size, --bench # adds timings). Not a ctest: whether the two agree is a property of the cuBLAS build, which this checks. @@ -976,6 +1416,18 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(gr_upmix_parity PRIVATE strata_prefill ) add_test(NAME gr_upmix_parity COMMAND gr_upmix_parity) set_tests_properties(gr_upmix_parity PROPERTIES SKIP_RETURN_CODE 77) + # the two kernels of the layer-major prompt path (STRATA_PREFILL_LAYER_MAJOR=1, #3976): moe_shared_init and + # moe_scatter_add against a host reference, bitwise for the scatter (GPU, synthetic, no model) + add_executable(lm_kernels_parity src/prefill/lm_kernels_parity.cu) + target_link_libraries(lm_kernels_parity PRIVATE strata_prefill ) + add_test(NAME lm_kernels_parity COMMAND lm_kernels_parity) + set_tests_properties(lm_kernels_parity PROPERTIES SKIP_RETURN_CODE 77) + # hc_q8_to_bf16 on the stream it is given: the layer-major prompt walk expanded a STRATA_HC_REQ8 + # hyper-connection projection on the default stream while its GEMMs read another. Synthetic, no model. + add_executable(hc_q8_stream_test tests/cuda/hc_q8_stream_test.cu) + target_link_libraries(hc_q8_stream_test PRIVATE strata_prefill ) + add_test(NAME hc_q8_stream COMMAND hc_q8_stream_test) + set_tests_properties(hc_q8_stream PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) endif() # native_expert_grouped's group stride and fused SwiGLU + q8_1, bitwise vs the launches before them (GPU, synthetic, # no model; --bench adds v1/new timings of a window's 48 calls in a graph) @@ -998,18 +1450,32 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME gfx906_gdn_rec_head COMMAND gfx906_gdn_rec_head) set_tests_properties(gfx906_gdn_rec_head PROPERTIES TIMEOUT 120) endif() + if(STRATA_ENABLE_CUDA) + # the Volta prompt experts (gemm_iq_f16_grouped, STRATA_PF_WMMA) against a double reference; skipped below sm_70 + add_executable(pf_wmma_parity src/kernels/pf_wmma_parity.cpp) + target_include_directories(pf_wmma_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(pf_wmma_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME pf_wmma_parity COMMAND pf_wmma_parity) + set_tests_properties(pf_wmma_parity PROPERTIES SKIP_RETURN_CODE 77) + endif() add_executable(shared_expert_parity src/kernels/shared_expert_parity.cpp) target_include_directories(shared_expert_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME shared_expert_parity COMMAND shared_expert_parity --selftest) - # the split / batched verify-window kernels (from eddoursul's fork), bitwise vs the kernels they replace; CUDA only - if(STRATA_ENABLE_CUDA) + # the split / batched verify-window kernels (from eddoursul's fork), bitwise vs the kernels they replace + if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(verify_parity src/kernels/verify_parity.cpp) target_include_directories(verify_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(verify_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME verify_parity COMMAND verify_parity --selftest) endif() - + # BW-DENSE: the v3 read's weight-prefetch variants against the plain v3 read, bit for bit, and their cold-weight time + add_executable(gr_v3_screen src/kernels/gr_v3_screen.cpp) + target_include_directories(gr_v3_screen PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gr_v3_screen PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_executable(mmvf_unr_hash src/kernels/mmvf_unr_hash.cpp) + target_include_directories(mmvf_unr_hash PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(mmvf_unr_hash PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_executable(fused_gr_bench src/kernels/fused_gr_bench.cpp) target_include_directories(fused_gr_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(fused_gr_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) @@ -1031,6 +1497,26 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(gdn_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(gdn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME gdn_parity COMMAND gdn_parity --selftest) + # #3948: the same checks through the 4-blocks-a-head GDN step (the default on gfx1151), whose output-norm kernel writes the + # STRATA_QFUSE q8_1 image on its own + add_test(NAME gdn_parity_split COMMAND gdn_parity --selftest) + set_tests_properties(gdn_parity_split PROPERTIES ENVIRONMENT "STRATA_GDN_SPLIT=1") + + # v100/gdn-chunk: the chunked GDN prompt recurrence vs the token recurrence and a host reference (GPU, + # synthetic, no model). The chunked path changes the summation order - FP32-level, not bit-exact - so the + # test asserts measured error bounds, and --selftest pins them. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) + add_executable(gdn_chunk_parity src/kernels/gdn_chunk_parity.cpp) + target_include_directories(gdn_chunk_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gdn_chunk_parity PRIVATE strata_prefill ${_strata_gpu_runtime_target}) + add_test(NAME gdn_chunk_parity COMMAND gdn_chunk_parity --selftest) + set_tests_properties(gdn_chunk_parity PROPERTIES SKIP_RETURN_CODE 77) + + # v100/gdn-chunk: the micro benchmark (CUDA events, real GDN shapes): chunked vs recurrent prompt path. + add_executable(gdn_chunk_bench bench/gdn_chunk_bench.cpp) + target_include_directories(gdn_chunk_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gdn_chunk_bench PRIVATE strata_prefill ${_strata_gpu_runtime_target}) + endif() add_executable(s2_gemv_q8_parity src/kernels/s2_gemv_q8_parity.cpp) target_include_directories(s2_gemv_q8_parity PRIVATE ${_strata_gpu_include_directories}) @@ -1048,6 +1534,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(spec_verify_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME spec_verify_parity COMMAND spec_verify_parity) set_tests_properties(spec_verify_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0") + # the explicit mu / NULL verifier of the gated proposal (STRATA_SPEC_PROB=1, pick gate) against a CPU oracle + add_executable(spec_proposal_parity src/kernels/spec_proposal_parity.cpp) + target_include_directories(spec_proposal_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(spec_proposal_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME spec_proposal_parity COMMAND spec_proposal_parity) + set_tests_properties(spec_proposal_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0" TIMEOUT 120) # the same fixtures on the other two sampled paths: the one-block kernel and the 0.1.20 kernel add_test(NAME sampler_parity_one_block COMMAND sampler_parity --selftest) set_tests_properties(sampler_parity_one_block PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=1") @@ -1139,6 +1631,16 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(bf16_gemv_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME bf16_gemv_parity COMMAND bf16_gemv_parity --selftest) + # the V100 fusion work: every fused kernel against its unfused pipeline, bitwise, and the before/after + # CUDA-event timings at decode shapes (`--bench`). It is a .cu because it carries the unfused reference + # kernels it compares against. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) + add_executable(fusions_parity bench/micro/fusions_parity.cu) + target_include_directories(fusions_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(fusions_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME fusions_parity COMMAND fusions_parity) + endif() + add_executable(s_gemv_q8k_parity src/kernels/s_gemv_q8k_parity.cpp) target_include_directories(s_gemv_q8k_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(s_gemv_q8k_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) @@ -1175,6 +1677,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME ple_parity COMMAND ple_parity --selftest --in "${STRATA_PLE_FIXTURE_DIR}/ple_in.bin" --out "${STRATA_PLE_FIXTURE_DIR}/ple_out.bin" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + # STRATA_PLE_COMPACT: the raw IQ4_NL rows dequantized on the device against the host decode, bit for bit (synthetic, no model) + add_executable(ple_iq4nl_dequant_test src/kernels/ple_iq4nl_dequant_test.cpp) + target_include_directories(ple_iq4nl_dequant_test PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(ple_iq4nl_dequant_test PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME ple_iq4nl_dequant_test COMMAND ple_iq4nl_dequant_test) + set_tests_properties(ple_iq4nl_dequant_test PROPERTIES SKIP_RETURN_CODE 77) # Plan v0.3 P7: INT8 KV storage vs a host reference and vs the FP16 path (GPU, synthetic, no model). add_executable(kv_q8_parity src/kernels/kv_q8_parity.cpp) @@ -1241,11 +1749,36 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(platform_memory_test PRIVATE strata_core ${_strata_gpu_runtime_target}) add_test(NAME platform_memory_test COMMAND platform_memory_test) + # The pinned-memory headroom (pin_budget.hpp) against a simulated ceiling; skips without a GPU. + add_executable(pin_budget_test src/core/pin_budget_test.cpp) + target_link_libraries(pin_budget_test PRIVATE strata_core ${_strata_gpu_runtime_target}) + add_test(NAME pin_budget_test COMMAND pin_budget_test) + + # #3431: the expert arena's registered ranges keep their GPU aliases clear of the process's own memory (Windows HIP; else skips) + add_executable(pinned_alias_test src/core/pinned_alias_test.cpp) + target_link_libraries(pinned_alias_test PRIVATE strata_core ${_strata_gpu_runtime_target}) + add_test(NAME pinned_alias_test COMMAND pinned_alias_test) + set_tests_properties(pinned_alias_test PROPERTIES SKIP_RETURN_CODE 77) + + # #3350 / #3470: the conversation copy streams and events are pooled across short-lived threads (needs a device, else skips) + add_executable(conversation_copy_streams_test src/core/conversation_copy_streams_test.cpp) + target_include_directories(conversation_copy_streams_test PRIVATE include) + target_link_libraries(conversation_copy_streams_test PRIVATE strata_core ${_strata_gpu_runtime_target}) + add_test(NAME conversation_copy_streams_test COMMAND conversation_copy_streams_test) + set_tests_properties(conversation_copy_streams_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_executable(pinned_shared_test src/core/pinned_shared_test.cpp) target_link_libraries(pinned_shared_test PRIVATE strata_core ${_strata_gpu_runtime_target}) add_test(NAME pinned_shared_test COMMAND pinned_shared_test) endif() + if(WIN32) # the replicas' shared expert arena as a named section (src/core/pinned.cu): two arenas, a child process, the last handle + add_executable(pinned_shared_win_test src/core/pinned_shared_win_test.cpp) + target_include_directories(pinned_shared_win_test PRIVATE include) + target_link_libraries(pinned_shared_win_test PRIVATE strata_core ${_strata_gpu_runtime_target}) + add_test(NAME pinned_shared_win_test COMMAND pinned_shared_win_test) + set_tests_properties(pinned_shared_win_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180) + endif() # Plan v0.3 P2: the n-gram table read straight from the SSD. The selftest needs only the CPU and a temp file. add_executable(ple_reader_test src/ngram/ple_reader_test.cpp) @@ -1253,6 +1786,29 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(ple_reader_test PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME ple_reader_selftest COMMAND ple_reader_test --selftest) + # #3602: the same reader under load - several clients, a tiny row cache, one in-flight slot, injected delays, rows on + # every page phase, late-writer checks, the reader after a failed read. CPU and a temp file only; 77 = no direct reads here. + add_executable(ple_reader_stress_test src/ngram/ple_reader_stress_test.cpp) + target_include_directories(ple_reader_stress_test PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(ple_reader_stress_test PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME ple_reader_stress COMMAND ple_reader_stress_test) + set_tests_properties(ple_reader_stress PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + + # 0.2.7: the PLE residency rule (table + expert arena + headroom); header-only, needs nothing + add_executable(ple_residency_test src/core/ple_residency_test.cpp) + target_include_directories(ple_residency_test PRIVATE include) + add_test(NAME ple_residency_test COMMAND ple_residency_test) + + # #4474: the automatic expert cache's slot rule (the late allocation priced); header-only, needs nothing + add_executable(auto_cache_test src/core/auto_cache_test.cpp) + target_include_directories(auto_cache_test PRIVATE include) + add_test(NAME auto_cache_test COMMAND auto_cache_test) + + # 0.2.7 (#3911): the qwen35 host sampler's penalties on a short (draft-vocab) logit row; header-only, CPU + add_executable(qwen35_sampling_test src/qwen35/sampling_test.cpp) + target_include_directories(qwen35_sampling_test PRIVATE include) + add_test(NAME qwen35_sampling_test COMMAND qwen35_sampling_test) + # The GPU test runs ON THE TARGET PC. `--selftest` allocates # and writes real VRAM, so a machine without a device fails this test rather than skipping it silently - # which is correct: an engine that targets one GPU should not report a pass for having no GPU. @@ -1310,6 +1866,30 @@ if(STRATA_BUILD_TESTS) add_executable(arch_defaults_test src/core/arch_defaults_test.cpp src/core/arch_defaults.cpp) target_include_directories(arch_defaults_test PRIVATE include) add_test(NAME arch_defaults_test COMMAND arch_defaults_test) + # STRATA_AMD_COMMUNITY_TUNING: the switch turns each community-made AMD change off (header only; run from the source tree) + add_executable(amd_community_test src/core/amd_community_test.cpp) + target_include_directories(amd_community_test PRIVATE include) + target_compile_definitions(amd_community_test PRIVATE EXPECT_DOT_BUILT=1) + add_test(NAME amd_community_test COMMAND amd_community_test WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + add_executable(amd_community_test_dot_off src/core/amd_community_test.cpp) # the -DSTRATA_AMD_COMMUNITY_TUNING=OFF build + target_include_directories(amd_community_test_dot_off PRIVATE include) + target_compile_definitions(amd_community_test_dot_off PRIVATE EXPECT_DOT_BUILT=0 STRATA_AMD_COMMUNITY_DOT_OFF=1) + add_test(NAME amd_community_test_dot_off COMMAND amd_community_test_dot_off WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + add_executable(gfx12_extra_test src/core/gfx12_extra_test.cpp src/core/arch_defaults.cpp) # gfx12 extra defaults and their off switches + target_include_directories(gfx12_extra_test PRIVATE include) + add_test(NAME gfx12_extra_test COMMAND gfx12_extra_test) + add_executable(nv_defaults_test src/core/nv_defaults_test.cpp src/core/nv_defaults.cpp) # the sm_121 (GB10) table and its two off switches + target_include_directories(nv_defaults_test PRIVATE include) + add_test(NAME nv_defaults_test COMMAND nv_defaults_test) + add_executable(kva_test src/prefill/kva_test.cpp) # KVA: the switch, the automatic tail, the reasons a read is turned away + target_include_directories(kva_test PRIVATE include) + add_test(NAME kva_test COMMAND kva_test) + add_executable(adapt_async_default_test src/core/adapt_async_default_test.cpp) + target_include_directories(adapt_async_default_test PRIVATE include) + add_test(NAME adapt_async_default_test COMMAND adapt_async_default_test) + add_executable(uma_cache_test src/core/uma_cache_test.cpp) + target_include_directories(uma_cache_test PRIVATE include) + add_test(NAME uma_cache_test COMMAND uma_cache_test) add_executable(suffix_drafter_test src/spec/suffix_drafter_test.cpp) target_link_libraries(suffix_drafter_test PRIVATE strata_spec) add_test(NAME suffix_drafter_test COMMAND suffix_drafter_test) @@ -1319,6 +1899,15 @@ if(STRATA_BUILD_TESTS) add_executable(draft_policy_test src/spec/draft_policy_test.cpp) target_link_libraries(draft_policy_test PRIVATE strata_spec) add_test(NAME draft_policy_test COMMAND draft_policy_test) + add_executable(window_rule_test src/spec/window_rule_test.cpp) # which rule picks the window / whose q judges it, by the active draft source + target_include_directories(window_rule_test PRIVATE include) + add_test(NAME window_rule_test COMMAND window_rule_test) + add_executable(draft_vocab_test src/spec/draft_vocab_test.cpp) # the DFlash2-alone start's draft-vocabulary choice (a build's packaged default subset; the error elsewhere) + target_include_directories(draft_vocab_test PRIVATE include) + add_test(NAME draft_vocab_test COMMAND draft_vocab_test) + add_executable(spec_start_test src/spec/spec_start_test.cpp) + target_include_directories(spec_start_test PRIVATE include) + add_test(NAME spec_start_test COMMAND spec_start_test) endif() if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) add_executable(message_boundary_test src/program/message_boundary_test.cpp) @@ -1332,6 +1921,28 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) add_executable(conv_cache_test src/program/conv_cache_test.cpp) target_include_directories(conv_cache_test PRIVATE include) add_test(NAME conv_cache_test COMMAND conv_cache_test) + # --adapt-decay outside 0..1 falls back to 0.7 with a line (#1284; header-only, CPU) + add_executable(adapt_decay_test src/program/adapt_decay_test.cpp) + target_include_directories(adapt_decay_test PRIVATE include) + add_test(NAME adapt_decay_test COMMAND adapt_decay_test) + # the window limits (8 rows, or 16 in a wide CUDA / HIP build) and the pipelined-window probe (header-only, CPU) + add_executable(window_limits_test src/core/window_limits_test.cpp) + target_include_directories(window_limits_test PRIVATE include) + add_test(NAME window_limits_test COMMAND window_limits_test) + # #4677: the accepted rows a request commits are bounded to what it can emit (header-only, CPU; 2,736 cases against the old output loop) + add_executable(serve_stop_bound_test tests/core/serve_stop_bound_test.cpp) + target_include_directories(serve_stop_bound_test PRIVATE include) + target_compile_features(serve_stop_bound_test PRIVATE cxx_std_17) + add_test(NAME serve_stop_bound_test COMMAND serve_stop_bound_test) + # the --lookup-max-t default (12 on the 8-row CUDA serve, off on Metal, HIP and every other case; header-only, CPU) + add_executable(lookup_default_test tests/core/lookup_default_test.cpp) + target_include_directories(lookup_default_test PRIVATE include) + target_compile_features(lookup_default_test PRIVATE cxx_std_17) + add_test(NAME lookup_default_test COMMAND lookup_default_test) + # which window-size graph is freed when the next one does not fit (#3702; header-only, CPU) + add_executable(window_evict_test src/core/window_evict_test.cpp) + target_include_directories(window_evict_test PRIVATE include) + add_test(NAME window_evict_test COMMAND window_evict_test) # which path computes the draft layer's prompt K/V, and STRATA_SPLIT_MTP_BATCH's parsing (header-only, CPU) add_executable(draft_kv_plan_test src/program/draft_kv_plan_test.cpp) target_include_directories(draft_kv_plan_test PRIVATE include) @@ -1340,10 +1951,33 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) add_executable(coupled_draft_test src/core/coupled_draft_test.cpp) target_include_directories(coupled_draft_test PRIVATE include) add_test(NAME coupled_draft_test COMMAND coupled_draft_test) + # #4590: the penalty window is the current reply by default, STRATA_PENALTY_PROMPT=1 the old prompt + reply window (header-only, CPU) + add_executable(penalty_window_test src/kernels/penalty_window_test.cpp) + target_include_directories(penalty_window_test PRIVATE include) + add_test(NAME penalty_window_test COMMAND penalty_window_test) + # the penalty-history rows of a batch window, per slot (header-only, CPU) + add_executable(slot_history_test src/kernels/slot_history_test.cpp) + target_include_directories(slot_history_test PRIVATE include) + add_test(NAME slot_history_test COMMAND slot_history_test) # probabilistic draft acceptance (STRATA_SPEC_PROB): rejection sampling preserves p - chi-square over 2M trials per case (CPU) add_executable(spec_prob_test src/core/spec_prob_test.cpp) target_include_directories(spec_prob_test PRIVATE include) add_test(NAME spec_prob_test COMMAND spec_prob_test) + # gated proposal packets (STRATA_SPEC_PROB=1, pick gate): masked measure, NULL tail, root rescue (header-only, CPU) + add_executable(gated_proposal_test src/core/gated_proposal_test.cpp) + target_include_directories(gated_proposal_test PRIVATE include) + add_test(NAME gated_proposal_test COMMAND gated_proposal_test) + # the admission law of that packet, enumerated exactly (no Monte Carlo), in the three gate modes (CPU) + add_executable(spec_admission_test src/core/spec_admission_test.cpp src/spec/draft_policy.cpp) + target_include_directories(spec_admission_test PRIVATE include) + add_test(NAME spec_admission_default COMMAND ${CMAKE_COMMAND} -E env --unset=STRATA_SPEC_PROB_GATE $) + add_test(NAME spec_admission_pick COMMAND ${CMAKE_COMMAND} -E env STRATA_SPEC_PROB_GATE=pick $ pick) + add_test(NAME spec_admission_top COMMAND ${CMAKE_COMMAND} -E env STRATA_SPEC_PROB_GATE=top $ top) + add_test(NAME spec_admission_exact_top_only COMMAND ${CMAKE_COMMAND} -E env STRATA_SPEC_PROB_GATE=TOP $ pick) + # the per-card window cap of --draft dflash2 (header-only, CPU) + add_executable(draft_cap_test src/core/draft_cap_test.cpp) + target_include_directories(draft_cap_test PRIVATE include) + add_test(NAME draft_cap_test COMMAND draft_cap_test) # the f32 -> bf16 rounding against ggml's, NaN included, over every f32 bit pattern (header-only, CPU) add_executable(bf16_bits_test src/kernels/bf16_bits_test.cpp) target_include_directories(bf16_bits_test PRIVATE include) @@ -1358,8 +1992,13 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) add_test(NAME batch_groups_test COMMAND batch_groups_test) endif() -add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp - src/kernels/cpu/expert_layout.cpp src/kernels/cpu/q2_avx2.cpp) +if(STRATA_CPU_X86) + add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp + src/kernels/cpu/expert_layout.cpp src/kernels/cpu/q2_avx2.cpp src/kernels/cpu/hadamard.cpp) +else() + add_library(strata_kernels_cpu STATIC src/kernels/cpu/portable.cpp src/kernels/cpu/pool.cpp + src/kernels/cpu/expert_layout.cpp src/kernels/cpu/hadamard.cpp) +endif() target_include_directories(strata_kernels_cpu PUBLIC include) # Plan v0.3 P6: only the kernel files get the AVX-512 / AVX2 flags; the pool and the probe run on any x86-64, # and the engine picks the kernels at run time (cpu_avx512_ok). @@ -1424,11 +2063,25 @@ if(STRATA_NATIVE_EXPERTS) set(GGML_BACKEND_DL OFF CACHE BOOL "" FORCE) set(GGML_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(GGML_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) - if(STRATA_PORTABLE) + if(STRATA_PORTABLE AND NOT STRATA_CPU_X86) + # arm64 (DGX Spark: Cortex-X925 + A725): ggml-cpu for any Armv8.2 CPU with dot product, FP16 and int8 matmul instead of the build + # host's, so the engine built here does not depend on which core the compiler ran on. Without it GGML_NATIVE OFF would leave + # ggml-cpu at plain armv8-a, and a native pack's CPU experts would lose the NEON dot products. + set(GGML_NATIVE OFF CACHE BOOL "" FORCE) + set(STRATA_ARM64_ARCH "armv8.2-a+dotprod+fp16+i8mm" CACHE STRING "arm64: ggml-cpu's -march for a STRATA_PORTABLE build") + set(GGML_CPU_ARM_ARCH "${STRATA_ARM64_ARCH}" CACHE STRING "" FORCE) + elseif(STRATA_PORTABLE) set(GGML_NATIVE OFF CACHE BOOL "" FORCE) foreach(_f GGML_AVX GGML_AVX2 GGML_FMA GGML_F16C GGML_BMI2) set(${_f} ON CACHE BOOL "" FORCE) endforeach() + # The DeepSeek engine (STRATA_BUILD_DSV41) builds ggml-cpu with BMI2 OFF: ggml's IQ1_S / IQ1_M dots use _pdep_u64 with it, and AMD + # Zen 1/2 run PDEP in microcode (EPYC 7452, IQ1_M one-token dot 1.8 GB/s against 32 GB/s without it; IQ1_S 2.3 against 37). The + # results are bit-identical either way (ds4_gg_bench --dump, types 19 and 29, 1-16 tokens). Other engines keep BMI2 until their + # next rebuild is looked at: no Qwen package changes with this commit. + if(STRATA_BUILD_DSV41) + set(GGML_BMI2 OFF CACHE BOOL "" FORCE) + endif() elseif(STRATA_ISA_FLOOR) # the experimental older-CPU build (STRATA_ISA_FLOOR above): one ggml-cpu for the floor, ggml's "sandybridge" # feature set (SSE4.2 + AVX) or SSE4.2 alone - not the build host's, which may be newer than the PC it runs on. @@ -1464,10 +2117,17 @@ if(STRATA_NATIVE_EXPERTS) endif() # part of strata_kernels_cpu (the pool calls these and they call its CPU probe: one library, so GNU ld's # one-pass static linking has no cycle to resolve) - target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp - src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp - src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp - src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp) + target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp) + if(STRATA_CPU_X86) + target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/iq_avx2.cpp + src/kernels/cpu/kq_avx2.cpp src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp + src/kernels/cpu/iq_avx1.cpp src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp + src/kernels/cpu/tq_cpu.cpp src/kernels/cpu/tq_avx2.cpp src/kernels/cpu/tq_avx512.cpp) + else() + # the trellis dispatcher alone (the DeepSeek engine's CPU lane and Gyro): tq_cpu.cpp runs its scalar rows when the x86 units are + # not compiled (the Metal build does the same) + target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/tq_cpu.cpp) + endif() target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml) if(MSVC) set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp @@ -1475,6 +2135,8 @@ if(STRATA_NATIVE_EXPERTS) set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") + set_source_files_properties(src/kernels/cpu/tq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") + set_source_files_properties(src/kernels/cpu/tq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") # the router lookahead's AVX1 dot (older CPUs; called behind cpu_avx1_ok): no FMA, no 256-bit integer ops set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") # the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): 128-bit integer lanes, @@ -1484,10 +2146,14 @@ if(STRATA_NATIVE_EXPERTS) set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") else() set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp PROPERTIES COMPILE_OPTIONS - "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") + "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mavx512vpopcntdq;-mbmi2;-mf16c;-mfma") set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + # the trellis kernels: AVX2 + FMA, and AVX-512 F/BW/VL/VBMI/VNNI (exactly what cpu_avx512_ok() checks) + set_source_files_properties(src/kernels/cpu/tq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + set_source_files_properties(src/kernels/cpu/tq_avx512.cpp PROPERTIES COMPILE_OPTIONS + "-mavx512f;-mavx512bw;-mavx512vl;-mavx512vnni;-mavx512vbmi;-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx") # the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): SSE4.2 + AVX with # AVX2/FMA/F16C explicitly off, so a -march=native build host cannot leak AVX2 code into the file that @@ -1513,10 +2179,27 @@ if(STRATA_NATIVE_EXPERTS) target_link_libraries(dequant_q5_1_test PRIVATE strata_artifact ggml-base) add_test(NAME dequant_q5_1_test COMMAND dequant_q5_1_test) endif() + # the x86 kernels' parity programs and benches (to the matching endif below): not on arm64, which has none of those kernels + if(STRATA_CPU_X86) # the router lookahead's dot on each rung this CPU has (AVX2, the older CPUs' AVX1) against a double reference add_executable(router_dot_parity src/kernels/cpu/router_dot_parity.cpp) target_link_libraries(router_dot_parity PRIVATE strata_kernels_cpu) if(STRATA_BUILD_TESTS) + # a token's native expert rows are the same bits at every number of tokens that share its expert (window-invariant arithmetic) + add_executable(native_arithmetic_parity src/kernels/cpu/native_arithmetic_parity.cpp) + target_link_libraries(native_arithmetic_parity PRIVATE strata_kernels_cpu) + add_test(NAME native_arithmetic_parity COMMAND native_arithmetic_parity) + add_test(NAME native_arithmetic_parity_avx COMMAND ${CMAKE_COMMAND} -E env + STRATA_FORCE_ISA=avx $) + add_test(NAME native_arithmetic_parity_kq256 COMMAND ${CMAKE_COMMAND} -E env + STRATA_KQ256=1 $) + add_test(NAME native_arithmetic_parity_mt1 COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ_MT_MIN=1 $) + add_test(NAME native_arithmetic_parity_no512 COMMAND ${CMAKE_COMMAND} -E env STRATA_NO_IQ512=1 $) + add_test(NAME native_arithmetic_parity_ggml COMMAND ${CMAKE_COMMAND} -E env STRATA_NO_IQ512=1 STRATA_NO_IQ256=1 STRATA_NO_IQ4NL=1 $) + add_test(NAME native_arithmetic_parity_nvfp4_avx2 COMMAND ${CMAKE_COMMAND} -E env + STRATA_NO_NVFP4_512=1 $) + add_test(NAME native_arithmetic_parity_nvfp4_ggml COMMAND ${CMAKE_COMMAND} -E env + STRATA_NO_NVFP4_512=1 STRATA_NO_NVFP4_256=1 $) add_executable(pool_tasks_test src/kernels/cpu/pool_tasks_test.cpp) target_link_libraries(pool_tasks_test PRIVATE strata_kernels_cpu) add_test(NAME pool_tasks_test COMMAND pool_tasks_test) @@ -1528,6 +2211,14 @@ if(STRATA_NATIVE_EXPERTS) # against ggml-cpu's dot, on random blocks; --bench: ms per expert on one thread, the weights streamed from DRAM add_executable(iq_avx2_parity src/kernels/cpu/iq_avx2_parity.cpp) target_link_libraries(iq_avx2_parity PRIVATE strata_kernels_cpu) + # the 512-bit i-quant rows against ggml-cpu's dot: the exact rows bit for bit at 1-4 tokens, the engine's multi-token rows to float + # rounding, with the grid lookups as scalar loads and as gathers (SKIP without AVX-512) + add_executable(iq512_gather_parity src/kernels/cpu/iq512_gather_parity.cpp) + target_link_libraries(iq512_gather_parity PRIVATE strata_kernels_cpu) + if(STRATA_BUILD_TESTS) + add_test(NAME iq512_gather_parity_scalar COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ_GATHER=0 $) + add_test(NAME iq512_gather_parity_gather COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ_GATHER=1 $) + endif() # MODEL-UPDATE: the pool's expert rows per format on T threads against the RAM bandwidth (a benchmark, no test) add_executable(kq_cpu_bench src/kernels/cpu/kq_cpu_bench.cpp) target_link_libraries(kq_cpu_bench PRIVATE strata_kernels_cpu) @@ -1550,7 +2241,42 @@ if(STRATA_NATIVE_EXPERTS) add_test(NAME q8k_quant_parity COMMAND q8k_quant_parity) add_test(NAME q8k_quant_parity_avx COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_ISA=avx $) endif() + endif() # STRATA_CPU_X86 set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + # APR: the agention llama.cpp fork has MMQ instances for its trellis expert types (f62fdead0); any other ggml + # tree leaves them to the FP16 prompt path + if(STRATA_GGML_DIR AND EXISTS "${STRATA_GGML_DIR}/ggml/src/ggml-cuda/template-instances/mmq-instance-tqk6.cu") + list(APPEND _strata_mmq_types tq2_t tqk6 tqk7) + # Gyro-L's pair trellis (types 147-149): the same fork's ggml has their MMQ instances + if(EXISTS "${STRATA_GGML_DIR}/ggml/src/ggml-cuda/template-instances/mmq-instance-tqp5.cu") + list(APPEND _strata_mmq_types tqp5 tqp6 tqp7) + set(_strata_mmq_tqp ON) # moe_mmq.cu names GGML_TYPE_TQP5-7 only where the ggml has them (STRATA_MMQ_TQP) + endif() + set(_strata_mmq_tq ON) + elseif(STRATA_MMQ_TQ_OVERLAY AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)) + # an upstream llama.cpp: the trellis MMQ instances come from an overlay of the pinned ggml-cuda headers written at + # configure time (cmake/strata_ggml_tq_overlay.cmake); off with a message if the llama.cpp tree is not the pinned one + if(STRATA_GGML_DIR) + set(_strata_tq_llama "${STRATA_GGML_DIR}") + else() + set(_strata_tq_llama "${strata_llamacpp_SOURCE_DIR}") + endif() + include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/strata_ggml_tq_overlay.cmake) + set(_strata_tq_overlay_dir "${CMAKE_BINARY_DIR}/ggml-tq-overlay") + strata_ggml_tq_overlay("${_strata_tq_llama}" "${_strata_tq_overlay_dir}") + if(STRATA_TQ_OVERLAY_OK) + configure_file(third_party/ggml/ggml-common-tq.h "${_strata_tq_overlay_dir}/ggml-common-tq.h" COPYONLY) + configure_file(src/kernels/cuda/tq_lut_i8.cuh "${_strata_tq_overlay_dir}/tq_lut_i8.cuh" COPYONLY) + set(_strata_mmq_tq ON) + set(_strata_mmq_tqp ON) # the overlay adds the pair-trellis enumerators and instances + set(_strata_mmq_tq_overlay ON) + message(STATUS "trellis MMQ (Gyro prompts): overlay on the pinned ggml-cuda in ${_strata_tq_overlay_dir}") + if(STRATA_BUILD_TESTS) + add_test(NAME ggml_tq_overlay COMMAND ${CMAKE_COMMAND} -DLLAMA=${_strata_tq_llama} + -DOUT=${CMAKE_BINARY_DIR}/ggml-tq-overlay-test -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/ggml_tq_overlay_test.cmake) + endif() + endif() + endif() # #296: OrcaRouter Q4_K_S's Q5_0 experts (Q4_K and Q5_1 come with STRATA_MMQ_KQUANTS on CUDA, S5's branch) if(STRATA_ORCA_Q4KS_MMQ) list(APPEND _strata_mmq_types q5_0) @@ -1565,11 +2291,21 @@ if(STRATA_NATIVE_EXPERTS) set(_strata_gg ${strata_llamacpp_SOURCE_DIR}/ggml) endif() set(_strata_mmq ${_strata_gg}/src/ggml-cuda) + set(_strata_quantize_cu ${_strata_mmq}/quantize.cu) # the overlay's copy when the trellis overlay is on: it includes mmq.cuh + if(_strata_mmq_tq_overlay) + set(_strata_quantize_cu ${_strata_tq_overlay_dir}/quantize.cu) + endif() # #136: the Q2_0 pack's prompt experts on Strata's own int8 kernels (moe_fused.cu, opt-in STRATA_PF_FUSED=1; CUDA # only: the HIP branch below keeps MMQ, and an sm_75 device or an sm_75-only build reports them unavailable) add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu src/prefill/mmq_nvfp4_w4a8.cu - src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu) + src/prefill/ggml_cuda_host.cu ${_strata_quantize_cu}) + if(STRATA_EXPERIMENTAL_SM60 AND NOT STRATA_HIP_GFX906) + # GP100 (sm_60): a resident layer's experts weight-stationary, one launch per product (moe_ws.hpp; opt-in at + # run time, STRATA_MMQ_WS=1, and only where every visible GPU is cc 6.0) + target_sources(strata_mmq PRIVATE src/prefill/moe_ws.cu src/prefill/moe_ws_gu_iq2.cu src/prefill/moe_ws_gu_iq3.cu + src/prefill/moe_ws_down.cu) + endif() # q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and # STRATA_MMQ_KQUANTS q4_k q5_k q5_1 q6_k, the experts of Unsloth's UD-Q4/Q5/Q6_K_XL (docs/QUANTS.md; the dispatch # follows eddoursul/Strata 7706c1b). MODEL-UPDATE Phase 1: on CUDA they are a library of their own, strata_kq @@ -1587,10 +2323,23 @@ if(STRATA_NATIVE_EXPERTS) foreach(_t IN LISTS _strata_mmq_cuda_types) target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu) endforeach() + if(_strata_mmq_tq_overlay) + foreach(_t tq2_t tqk6 tqk7 tqp5 tqp6 tqp7) + target_sources(strata_mmq PRIVATE ${_strata_tq_overlay_dir}/template-instances/mmq-instance-${_t}.cu) + endforeach() + # first on the include path: the patched mmq.cuh / ggml.h shadow the pinned ones for this target only + target_include_directories(strata_mmq BEFORE PRIVATE ${_strata_tq_overlay_dir} ${_strata_tq_overlay_dir}/include) + endif() # NVFP4: W4A8 (default) in mmq_nvfp4_w4a8.cu with the plain architectures; the opt-in W4A4 needs RTX 50's FP4 MMA, # which exists only in the arch-specific target, so its one unit alone is built with 12x -> 12xa (the default # binary is unchanged and runs on sm_121; a card without that image falls back to W4A8 at run time) set(_strata_w4a4_archs ${CMAKE_CUDA_ARCHITECTURES}) + # `native` is first replaced by the detected architectures (e.g. 120-real), so the 12x -> 12xa rewrite below applies + # to it too: with plain sm_120 ptxas refuses the FP4 MMA of this one unit (#4023) + if("native" IN_LIST _strata_w4a4_archs AND CMAKE_CUDA_ARCHITECTURES_NATIVE) + list(REMOVE_ITEM _strata_w4a4_archs native) + list(APPEND _strata_w4a4_archs ${CMAKE_CUDA_ARCHITECTURES_NATIVE}) + endif() # (two steps: CMake before 3.29 rejects a \2 whose optional group did not match, "120" alone) list(TRANSFORM _strata_w4a4_archs REPLACE "^(12[0-9])$" "\\1a") list(TRANSFORM _strata_w4a4_archs REPLACE "^(12[0-9])-(real|virtual)$" "\\1a-\\2") @@ -1690,8 +2439,18 @@ if(STRATA_NATIVE_EXPERTS) if(STRATA_ORCA_Q4KS_MMQ) target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) endif() + if(_strata_mmq_tq) + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TQ=1) + endif() + if(_strata_mmq_tqp) + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TQP=1) + endif() target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) + if(STRATA_EXPERIMENTAL_SM60 AND NOT STRATA_HIP_GFX906) + # the weight-stationary experts (moe_ws.hpp) are in strata_mmq: the prompt path may take them (STRATA_MMQ_WS=1) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_WS=1) + endif() if(STRATA_BUILD_TESTS) # #136: the fused int8 experts against a double-precision reference and the MMQ path (exit 77 below sm_80) add_executable(prefill_fused_moe_test tests/cuda/prefill_fused_moe_test.cpp) @@ -1703,12 +2462,40 @@ if(STRATA_NATIVE_EXPERTS) target_link_libraries(prefill_fused_iq_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) add_test(NAME prefill_fused_iq_test COMMAND prefill_fused_iq_test) set_tests_properties(prefill_fused_iq_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + # the opt-in STRATA_PF_FUSED_Q2N=1 on its own (the test leaves STRATA_PF_FUSED unset): the native Q2_0 pack's Q2_0 / Q2_0 + # layers on sm_80+ (77 below sm_80 and without a card) + add_test(NAME prefill_fused_iq_test_q2n COMMAND prefill_fused_iq_test "--only=Q2_0 / Q2_0" --unset-pf-fused) + set_tests_properties(prefill_fused_iq_test_q2n PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_Q2N=1" SKIP_RETURN_CODE 77 TIMEOUT 600) + # the opt-in STRATA_PF_FUSED_NT=256 kernels (256 threads, two blocks a multiprocessor, two-pass weight loads) against the + # same references; the batches of the test reach them through the Batch overload of experts_native (77 below sm_80) + add_test(NAME prefill_fused_iq_test_nt256 COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test_nt256 PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_NT=256" SKIP_RETURN_CODE 77 TIMEOUT 600) + # the opt-in STRATA_PF_FUSED_F16=1 (f16 mma, rounding level) and STRATA_PF_FUSED_WS=1 (warp-specialized, the same F16 products; + # about 101 KB of shared memory at its defaults, more than an sm_86 / sm_89 / sm_120 card's 99 KB, so it is set up on + # sm_80 and sm_90 cards and the test skips (77) elsewhere) + add_test(NAME prefill_fused_iq_test_f16 COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test_f16 PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_F16=1" SKIP_RETURN_CODE 77 TIMEOUT 600) + add_test(NAME prefill_fused_iq_test_ws COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test_ws PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_WS=1" SKIP_RETURN_CODE 77 TIMEOUT 600) # the MoE input quantized per token and scattered to its rows (mmq::quantize_scatter) against the per-row # gather: the same q8_1 bytes for every MMQ layout (--bench: both at 2K, 8K and 32K tokens) add_executable(prefill_mmq_scatter_test tests/cuda/prefill_mmq_scatter_test.cpp) target_link_libraries(prefill_mmq_scatter_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) add_test(NAME prefill_mmq_scatter_test COMMAND prefill_mmq_scatter_test) set_tests_properties(prefill_mmq_scatter_test PROPERTIES TIMEOUT 120) + if(STRATA_EXPERIMENTAL_SM60) + # mmq::swiglu_quant: swiglu + the down product's q8_1 rows in one kernel against the two, byte for byte + add_executable(prefill_swiglu_quant_test tests/cuda/prefill_swiglu_quant_test.cpp) + target_link_libraries(prefill_swiglu_quant_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_swiglu_quant_test COMMAND prefill_swiglu_quant_test) + set_tests_properties(prefill_swiglu_quant_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # the weight-stationary experts (STRATA_MMQ_WS) against the per-group MMQ, byte for byte, on random experts; the + # verdict is given on a compute capability 6.0 card only (77 elsewhere) + add_executable(prefill_ws_parity_test tests/cuda/prefill_ws_parity_test.cpp) + target_link_libraries(prefill_ws_parity_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_ws_parity_test COMMAND prefill_ws_parity_test) + set_tests_properties(prefill_ws_parity_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + endif() endif() if(STRATA_BUILD_TESTS AND _strata_mmq_tab_on) # STRATA_MMQ_DIRECT: the pointer-table MMQ bit for bit against the gathered MMQ (exit 77 below sm_80) @@ -1726,10 +2513,12 @@ if(STRATA_NATIVE_EXPERTS) set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120 ENVIRONMENT STRATA_MMQ_KQ=1) endif() # the NVFP4 expert products (w4a8 / w4a4, STRATA_PREFILL_NVFP4) against a double-precision reference - add_executable(mmq_nvfp4_parity src/prefill/mmq_nvfp4_parity.cpp) - target_link_libraries(mmq_nvfp4_parity PRIVATE strata_mmq ggml-base CUDA::cudart) - if(NOT MSVC) # its FP16 rounding helper uses the F16C intrinsics (GCC/Clang need the target flag) - target_compile_options(mmq_nvfp4_parity PRIVATE $<$:-mf16c>) + if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64|i[3-6]86)$") # its FP16 rounding helper is the x86 F16C intrinsics: not built on aarch64 + add_executable(mmq_nvfp4_parity src/prefill/mmq_nvfp4_parity.cpp) + target_link_libraries(mmq_nvfp4_parity PRIVATE strata_mmq ggml-base CUDA::cudart) + if(NOT MSVC) # GCC/Clang need the target flag + target_compile_options(mmq_nvfp4_parity PRIVATE $<$:-mf16c>) + endif() endif() # the routed-expert products (MMQ) timed at the prompt path's shapes (16 experts a launch) add_executable(mmq_expert_bench src/prefill/mmq_expert_bench.cpp) @@ -1743,6 +2532,10 @@ if(STRATA_NATIVE_EXPERTS) set(_strata_gg "${strata_llamacpp_SOURCE_DIR}/ggml") endif() set(_strata_mmq "${_strata_gg}/src/ggml-cuda") + set(_strata_quantize_cu "${_strata_mmq}/quantize.cu") # the overlay's copy when the trellis overlay is on: it includes mmq.cuh + if(_strata_mmq_tq_overlay) + set(_strata_quantize_cu "${_strata_tq_overlay_dir}/quantize.cu") + endif() if(NOT EXISTS "${_strata_mmq}/common.cuh" OR NOT EXISTS "${_strata_mmq}/quantize.cu") message(FATAL_ERROR "The selected GGML source is missing the ggml-cuda MMQ sources: ${_strata_mmq}") endif() @@ -1753,7 +2546,7 @@ if(STRATA_NATIVE_EXPERTS) src/prefill/moe_fused_iq.cu src/prefill/moe_f16_kq.cu src/prefill/ggml_cuda_host.cu - "${_strata_mmq}/quantize.cu") + "${_strata_quantize_cu}") if(STRATA_MMQ_KQUANTS) # the same K-quant instances as the CUDA branch: on HIP they serve the dense GGUF projections # of Gemm::native (STRATA_DENSE_MMQ=1), the mixed-quant packs' attention/PLE tensors @@ -1762,6 +2555,11 @@ if(STRATA_NATIVE_EXPERTS) foreach(_t IN LISTS _strata_mmq_types) list(APPEND _strata_mmq_sources "${_strata_mmq}/template-instances/mmq-instance-${_t}.cu") endforeach() + if(_strata_mmq_tq_overlay) + foreach(_t tq2_t tqk6 tqk7 tqp5 tqp6 tqp7) + list(APPEND _strata_mmq_sources "${_strata_tq_overlay_dir}/template-instances/mmq-instance-${_t}.cu") + endforeach() + endif() set_source_files_properties(${_strata_mmq_sources} PROPERTIES LANGUAGE HIP) # moe_fused.cu is Strata's own CUDA-shaped source: it takes the HIP compat headers, ggml's MMQ sources do not set_source_files_properties(src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu src/prefill/moe_f16_kq.cu @@ -1770,6 +2568,9 @@ if(STRATA_NATIVE_EXPERTS) target_include_directories(strata_mmq PRIVATE "${_strata_gg}/include" "${_strata_gg}/src" "${_strata_mmq}" PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + if(_strata_mmq_tq_overlay) + target_include_directories(strata_mmq BEFORE PRIVATE ${_strata_tq_overlay_dir} ${_strata_tq_overlay_dir}/include) + endif() target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP=1) if(STRATA_MMQ_KQUANTS) target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_KQUANTS=1) @@ -1777,6 +2578,12 @@ if(STRATA_NATIVE_EXPERTS) if(STRATA_ORCA_Q4KS_MMQ) target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) endif() + if(_strata_mmq_tq) + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TQ=1) + endif() + if(_strata_mmq_tqp) + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TQP=1) + endif() target_link_libraries(strata_mmq PUBLIC ggml-base hip::host roc::hipblas) target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) @@ -1825,21 +2632,34 @@ if(STRATA_NATIVE_EXPERTS) if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(native_expert_parity src/kernels/native_expert_parity.cpp) target_include_directories(native_expert_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_expert_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + # strata_engine: the --load-check mode runs the engine's start-up checks (NativeDense, check_experts_gguf) + target_link_libraries(native_expert_parity PRIVATE strata_engine strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) add_executable(native_expert_bench src/kernels/native_expert_bench.cpp) target_include_directories(native_expert_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + if(STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + # STRATA_EXPERT_NIBBLE (include/strata/core/expert_nibble.hpp): the 4-bit gate/up expert slots against the + # production kernels and the GGUF blobs, bit for bit, on a real model's layers (needs a GP100); --header: the + # contract's host half, no GPU + add_executable(iq_nibble_parity src/kernels/iq_nibble_parity.cpp) + target_include_directories(iq_nibble_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(iq_nibble_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ggml-base ${_strata_gpu_runtime_target}) + if(STRATA_BUILD_TESTS) + add_test(NAME iq_nibble_parity_header COMMAND iq_nibble_parity --header) + # the synthetic experts of every gate/up x down format pair, no model (skips with 77 on a card that is not a GP100) + add_test(NAME iq_nibble_parity_synthetic COMMAND iq_nibble_parity --synthetic-only) + set_tests_properties(iq_nibble_parity_synthetic PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 900) + endif() + endif() # MODEL-UPDATE: the dense Q8_0 GEMVs at the engine's shapes against the memory bandwidth (a benchmark, no test) add_executable(q8_gemv_bench src/kernels/q8_gemv_bench.cpp) target_include_directories(q8_gemv_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(q8_gemv_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - if(STRATA_ENABLE_CUDA) - # EXPDEC (docs/EXPERTDEC.md): the grouped experts' default kernels against STRATA_EXPDEC=1 at T = 1..4, bit for bit - # and in microseconds, on synthetic blobs read cold from DRAM - add_executable(expdec_bench EXCLUDE_FROM_ALL src/kernels/expdec_bench.cpp) - target_include_directories(expdec_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(expdec_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - endif() + # EXPDEC (docs/EXPERTDEC.md): the grouped experts' default kernels against STRATA_EXPDEC=1 at T = 1..4, bit for bit + # and in microseconds, on synthetic blobs read cold from DRAM + add_executable(expdec_bench EXCLUDE_FROM_ALL src/kernels/expdec_bench.cpp) + target_include_directories(expdec_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(expdec_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) # Unsloth UD-Q4_K_XL's three expert pairs (and Q8_0 alone, its embedding) on synthetic ggml-quantized weights # at 2560/640: GPU and CPU experts against the float reference, GPU dequantizers against to_float. @@ -1864,6 +2684,20 @@ if(STRATA_NATIVE_EXPERTS) set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120) endforeach() add_test(NAME native_expert_parity_q5_1_min COMMAND native_expert_parity --q5_1-min) + # APR: the trellis expert types and the Hadamard activation rotation, when ggml comes from the agention fork + # (the only tree with these types; marked by its ggml-cuda/tq.cuh) + if(STRATA_GGML_DIR AND EXISTS "${STRATA_GGML_DIR}/ggml/src/ggml-cuda/tq.cuh") + set(_strata_tq_pairs tqk6/tqk7 tq2_t/tq2_t) + if(EXISTS "${STRATA_GGML_DIR}/ggml/src/ggml-cuda/template-instances/mmq-instance-tqp5.cu") # Gyro-L's pair trellis + list(APPEND _strata_tq_pairs tqp5/tqp5 tqp6/tqp6 tqp7/tqp7) + endif() + foreach(_pair ${_strata_tq_pairs}) + string(REPLACE "/" "_" _name "${_pair}") + add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair}) + add_test(NAME native_expert_parity_hadamard_${_name} COMMAND native_expert_parity --synthetic-hadamard ${_pair}) + set_tests_properties(native_expert_parity_${_name} native_expert_parity_hadamard_${_name} PROPERTIES TIMEOUT 300) + endforeach() + endif() # #290: the BF16 token embedding (--embd-gguf) gathered and dequantized bit for bit add_test(NAME native_expert_parity_bf16_embd COMMAND native_expert_parity --bf16-embd) endif() @@ -1917,6 +2751,29 @@ if(STRATA_BUILD_TESTS) set_tests_properties(q2_bitplane_parity PROPERTIES ENVIRONMENT "STRATA_Q2_BITPLANE=1") endif() + if(STRATA_NATIVE_EXPERTS) + # APR port: a Hadamard-folded trellis expert (TQ2_T / TQK6 / TQK7) on the CPU path vs llama.cpp's graph for the + # same weights (synthetic; needs STRATA_GGML_DIR = a ggml with the trellis types, else it reports and fails) + add_executable(native_hadamard_test src/kernels/cpu/native_hadamard_test.cpp) + target_link_libraries(native_hadamard_test PRIVATE strata_kernels_cpu strata_artifact) + add_test(NAME native_hadamard_test COMMAND native_hadamard_test) + set_tests_properties(native_hadamard_test PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + # the CPU trellis kernels (tq_cpu.hpp): AVX2 / AVX-512 vs the scalar kernel bit for bit, vs ggml-cpu's vec_dot + # and to_float, plain and with the Hadamard rotation; `tq_cpu_parity --bench` is the micro-benchmark + add_executable(tq_cpu_parity src/kernels/cpu/tq_cpu_parity.cpp) + target_link_libraries(tq_cpu_parity PRIVATE strata_kernels_cpu) + add_test(NAME tq_cpu_parity COMMAND tq_cpu_parity) + add_test(NAME tq_cpu_parity_avx2 COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_AVX2=1 $) + set_tests_properties(tq_cpu_parity tq_cpu_parity_avx2 PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + # Gyro-L's pair trellis (types 147-149) and the older trellis rows on synthetic blocks, no ggml and no model: the scalar + # kernel against a bit-by-bit reference, every ISA bit for bit equal to scalar, the type predicates unchanged + add_executable(tqp_cpu_test src/kernels/cpu/tqp_cpu_test.cpp) + target_link_libraries(tqp_cpu_test PRIVATE strata_kernels_cpu) + add_test(NAME tqp_cpu_test COMMAND tqp_cpu_test) + add_test(NAME tqp_cpu_test_avx2 COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_AVX2=1 $) + set_tests_properties(tqp_cpu_test tqp_cpu_test_avx2 PROPERTIES TIMEOUT 120) + endif() + add_executable(expert_parity src/kernels/cpu/expert_parity.cpp) target_link_libraries(expert_parity PRIVATE strata_kernels_cpu) # The pack is a REQUIRED input, not an optional one: this test compares against a real expert blob, and a @@ -1927,6 +2784,27 @@ if(STRATA_BUILD_TESTS) add_executable(pool_test src/kernels/cpu/pool_test.cpp) target_link_libraries(pool_test PRIVATE strata_kernels_cpu) add_test(NAME pool_test COMMAND pool_test --selftest WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + # where the workers are placed (one per physical core by default) and --pool-cores (real pools, no model) + add_executable(pool_cores_test src/kernels/cpu/pool_cores_test.cpp) + target_link_libraries(pool_cores_test PRIVATE strata_kernels_cpu) + add_test(NAME pool_cores_test COMMAND pool_cores_test) + # the default CPU expert worker count on mock CPUs (8c/16t, 16c/32t, 64c/128t, 2-socket 128c/256t, ...) + add_executable(pool_plan_test src/kernels/cpu/pool_plan_test.cpp) + target_include_directories(pool_plan_test PRIVATE include) + add_test(NAME pool_plan_test COMMAND pool_plan_test) + # 0.2.2: when the pool splits per NUMA node by itself (a fake sysfs node folder, mock cores; STRATA_NUMA_POOL=0, one node = unchanged) + add_executable(numa_pool_test src/kernels/cpu/numa_pool_test.cpp) + target_include_directories(numa_pool_test PRIVATE include) + target_compile_features(numa_pool_test PRIVATE cxx_std_17) + add_test(NAME numa_pool_test COMMAND numa_pool_test) + # #3204: when the HIP start-up warm-up of hipBLAS may run (pure policy, no GPU) + add_executable(warm_policy_test src/prefill/warm_policy_test.cpp) + target_include_directories(warm_policy_test PRIVATE include) + add_test(NAME warm_policy_test COMMAND warm_policy_test) + # #4005: which streamed expert copies get a copied event (header-only, CPU) + add_executable(copy_events_test src/prefill/copy_events_test.cpp) + target_include_directories(copy_events_test PRIVATE include) + add_test(NAME copy_events_test COMMAND copy_events_test) # issue #29: tiny batches with sleeping workers, as on a big-VRAM card; a hang fails it add_executable(pool_stress src/kernels/cpu/pool_stress.cpp) target_link_libraries(pool_stress PRIVATE strata_kernels_cpu) @@ -1980,6 +2858,32 @@ if(STRATA_BUILD_TESTS) add_test(NAME aux_cpus_test COMMAND aux_cpus_test) endif() +# CUDA release kernels must not spill or keep a per-thread array in local memory: every access there is a round trip +# to device memory in the hottest loops the engine has, and nothing on the build machine says so without -Xptxas -v +# or a GPU. tools/check_cuda_spills.py reads the resource usage the compiler wrote into the kernel libraries +# (cuobjdump: STACK and LOCAL per entry function and per sm_) and fails on any kernel outside its ALLOWED table, which +# carries the measured allowance of the kernels that hold such an array on purpose. CUDA only: HIP has no cuobjdump. +if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS AND NOT STRATA_ENABLE_HIP AND NOT STRATA_HIP_GFX906) + find_package(Python3 QUIET COMPONENTS Interpreter) + if(Python3_Interpreter_FOUND) + set(_strata_spill_libs) + foreach(_t strata_kernels strata_core strata_engine strata_prefill strata_qwen35 strata_mmq strata_mmq_w4a4 strata_kq) + if(TARGET ${_t}) + list(APPEND _strata_spill_libs $) + endif() + endforeach() + add_test(NAME cuda_spill_guard COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/check_cuda_spills.py + --cuobjdump ${CUDAToolkit_BIN_DIR}/cuobjdump${CMAKE_EXECUTABLE_SUFFIX} ${_strata_spill_libs}) + set_tests_properties(cuda_spill_guard PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + if(NOT WIN32) # its stand-in demanglers are sh scripts + add_test(NAME check_cuda_spills_unit COMMAND ${Python3_EXECUTABLE} -m unittest tools.test_check_cuda_spills + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + endif() + else() + message(STATUS "strata: no python3 - the cuda_spill_guard test is NOT registered") + endif() +endif() + if(STRATA_BUILD_TESTS) enable_testing() # Model-level checks may be absent from source distributions. @@ -1996,6 +2900,23 @@ if(STRATA_HIP_GFX906) file(GLOB _strata_mmq_cu ${_strata_mmq}/*.cu ${_strata_mmq}/template-instances/*.cu) list(APPEND _strata_cu ${_strata_mmq_cu}) target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP) + # #3172: strata_mmq_w4a4 is built from llama.cpp's headers too; without GGML_USE_HIP its common.cuh took the CUDA vendor header + # (cuda.h, cuda_bf16.h: not found). Here it only reports that W4A4 (RTX 50's FP4 MMA) is not available. + if(TARGET strata_mmq_w4a4) + target_compile_definitions(strata_mmq_w4a4 PRIVATE GGML_USE_HIP) + endif() + # #3271: three more link errors of a 0.1.44+ gfx906 build, all sources that strata_mmq lists but the glob above never saw: + # the trellis overlay's quantize.cu and instances (they are generated into the build tree, so the glob missed them: CMake drops a + # .cu source whose language is not enabled) and moe_f16_kq.cu, which moe_fused_iq.cu calls (a stub here: no gfx11 device code, so + # f16kq::covers() answers false and the int8 kernels run, as on every other card) + if(_strata_mmq_tq_overlay) + set(_strata_tq_hip ${_strata_tq_overlay_dir}/quantize.cu) + foreach(_t tq2_t tqk6 tqk7 tqp5 tqp6 tqp7) + list(APPEND _strata_tq_hip ${_strata_tq_overlay_dir}/template-instances/mmq-instance-${_t}.cu) + endforeach() + list(APPEND _strata_cu ${_strata_tq_hip}) + endif() + target_sources(strata_mmq PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_f16_kq.cu) endif() set_source_files_properties(${_strata_cu} PROPERTIES LANGUAGE HIP) endif() @@ -2004,3 +2925,26 @@ if(STRATA_HIP_GFX906) add_executable(gfx906_qsa_query_swizzle_probe bench/gfx906_qsa_query_swizzle_probe.cpp) target_link_libraries(gfx906_qsa_query_swizzle_probe PRIVATE strata_kernels ${_strata_gpu_runtime_target}) endif() + +# ---- DeepSeek-V4.1 on a box with no GPU toolkit ------------------------------------------------ +# The whole DSV41 block above lives inside if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP), so with neither backend on +# -DSTRATA_BUILD_DSV41=ON was silently unused and the host-side benchmark could not be built at all (found on p1004, +# 2026-10-23: the CPU lane is exactly what a box without a usable GPU needs to measure). This branch builds the one target +# that has no device code, so the CPU-lane A/B runs anywhere. +if(STRATA_BUILD_DSV41 AND NOT STRATA_ENABLE_CUDA AND NOT STRATA_ENABLE_HIP AND NOT STRATA_HIP_GFX906) + message(STATUS "STRATA_BUILD_DSV41: no GPU backend, building the host-side benchmark only (ds4_gg_bench)") + if(STRATA_NATIVE_EXPERTS) + add_executable(ds4_gg_bench tests/dsv41/gg_dot_bench.cpp src/dsv41/ds4_gg_cpu.cpp) + target_include_directories(ds4_gg_bench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41 + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) + target_link_libraries(ds4_gg_bench PRIVATE strata_kernels_cpu Threads::Threads) + target_compile_definitions(ds4_gg_bench PRIVATE STRATA_DSV41_TQ_CPU=1) + endif() +endif() + +# ---- strata-split: the opt-in engine that splits every layer across 2-4 NVIDIA cards (src/split, from sFNX, MIT, John Fink) ---- +# OFF by default, Linux + CUDA only, no other target depends on it; see src/split/CMakeLists.txt and docs/SPLIT_ENGINE.md. +option(STRATA_BUILD_SPLIT "Build strata-split: sFNX's split-every-layer engine, host-memory exchange (Linux, CUDA or HIP gfx1201, 2-4 cards)" OFF) +if(STRATA_BUILD_SPLIT) + add_subdirectory(src/split) +endif() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000000..4efd7dd6804 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,122 @@ +# Contributing to Strata + +**AI assistance is welcome. The contributor is responsible for understanding the change and supplying real evidence.** + +These rules apply to issues, pull requests, benchmark reports, and the agents helping prepare them. +You should be able to explain every changed line and answer review questions about it. + +## Before starting + +1. Search [issues](https://github.com/Niko1221/Strata/issues) and + [pull requests](https://github.com/Niko1221/Strata/pulls), including closed discussions. Add new evidence to an + existing thread when it covers your problem. +2. Read [AGENTS.md](AGENTS.md) and the documentation for the component you want to change. +3. Get maintainer agreement on scope before substantial features, refactors, architecture changes, or changes to + defaults. Describe the user problem, proposed behavior, and tradeoffs in an issue first. Agreement on scope + does not guarantee a merge. Focused fixes and benchmark reports can go straight to a PR. +4. Keep one problem per PR. Update that PR after feedback; do not open competing attempts for the same change. + +Do not resubmit a declined proposal under a different title or through another agent. If new evidence changes +the situation, bring it to the original discussion and let a maintainer decide whether to reopen it. + +## Report a problem people can investigate + +Use the matching [issue form](https://github.com/Niko1221/Strata/issues/new/choose). A bug report should include: + +- The smallest steps or command that reproduce the problem, and the expected and actual behavior. +- Strata version or commit, OS, GPU and VRAM, and relevant model, quantization, and configuration. +- The exact error and relevant logs, with credentials and private content removed. +- Whether you reproduced it yourself. Label a finding based only on reading code or a scanner as + **unconfirmed static analysis**, and explain the suspected path without presenting it as an observed failure. + +Do not invent reproduction steps, errors, affected hardware, or severity. If you cannot reproduce something, +say what you inspected and what would verify the hypothesis. Feature requests should explain a concrete user +need and the current workaround. Questions should say what you tried and where you got stuck. + +Example structure, with placeholders to replace with actual observations: + +```text +Problem: +Environment: +Reproduce: +Expected: +Actual: +Evidence: +Reproduction status: +``` + +## Titles + +Every issue and pull request title starts with its area in square brackets, then a short description: `[Engine]`, `[GUI]`, `[TUI]`, +`[Benchmark]`, `[Docs]` or `[Other]`. For example `[Engine] fix decode stop on long prompts` or `[GUI] keep the model list after a tab +switch`. The issue forms ask for the area and a check on the title fails when the prefix is missing. + +## Prepare a focused pull request + +Lead with the problem and resulting behavior. Explain why the approach is needed, the important limits, and +any compatibility effects. Link the issue and scope agreement when applicable. A file-by-file narration or +an AI-generated summary of the diff is not a substitute for this explanation. + +- Keep unrelated formatting, cleanup, dependency changes, and speculative abstractions out of the PR. +- Add documentation where it changes what a user or developer needs to know. Avoid repeated summaries, + speculative roadmaps, and generated documentation with no actionable information. +- Preserve existing behavior outside the intended change. New features are opt-in; follow the default-path + and performance requirements in [AGENTS.md](AGENTS.md). +- Read the complete diff, including generated files, before submitting. Remove debugging output, secrets, + private paths, and accidental files. +- Prefer a small relevant regression check over tests that only restate the implementation. Documentation-only + changes need link, example, and consistency checks; they do not require GPU builds. + +## Show the validation you actually performed + +List exact commands, the revision and environment tested, and observed outcomes. Keep **passed**, **failed**, +and **not run** separate. Include relevant output or a log attachment. A command you suggest running is not +evidence that it passed; a CI run on a different revision is not validation of the submitted code. + +Build every backend a code change touches, including CUDA, HIP, and SYCL where applicable, before requesting +review. For changes that need hardware execution, report that execution separately from compilation. A mock, +static check, or successful build does not establish hardware correctness. If you lack a required environment, +keep the PR as a draft, identify the missing checks, and ask for targeted help in the same thread. Do not claim +compatibility you have not tested. + +Performance claims need before/after runs on the same hardware and workload, with every changed setting +identified. Preserve the individual runs, failures, and variability. Follow the +[community measurement guide](docs/COMMUNITY_BENCHMARKS.md); standard submissions will use the +[benchmark protocol](docs/BENCHMARK_PROTOCOL.md) once it is activated. One fast run does not justify changing a +default or claiming a speedup for other machines. + +Example PR body; placeholders are not test results: + +```text +Problem and result: +Related discussion: +Approach: +Validation: + Passed: + Failed: + Not run: +Limits: +``` + +## Rules for AI-assisted work + +Use agents to help investigate, implement, and explain work that you can review. Before submitting, verify +their claims against the source, actual command output, or a cited primary reference. + +Never submit fabricated measurements, invented test results, fake logs, or copied claims you have not checked. +Do not turn a repository scan into a batch of speculative issues or PRs. Consolidate related findings, establish +their effect, and submit the useful evidence. Do not present an agent's confidence or another model's approval +as validation. Keep review replies concise and address the requested change or evidence directly. + +Maintainers may request a smaller change, return a PR to draft, or close a submission that lacks evidence, +duplicates existing work, or ignores agreed scope. A smaller, understandable contribution with honest limits +is easier to review and maintain. + +## Share a benchmark + +A results-only PR should contain the human report, raw measurements, sanitized configuration, and supporting +logs. Keep it separate from engine changes and include poor results and failed requests. + +The [current community benchmark guide](docs/COMMUNITY_BENCHMARKS.md) remains available for measurements made +with today's tools. The [new protocol](docs/BENCHMARK_PROTOCOL.md) defines the draft standard and future approval +workflow. Its draft status must remain visible: existing reports are not automatically standard or approved. diff --git a/Dockerfile b/Dockerfile index 6430601886c..eba34a01126 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,119 +1,112 @@ -# syntax=docker/dockerfile:1 +# Strata, built FROM SOURCE (NVIDIA CUDA 13). The engine is compiled here, packaged as an engine component package and then +# installed into the same runtime image as the ready-made ones (docker/Dockerfile): same Terminal, same entrypoint, same /data volume. # -# Strata: Qwen3.8-Flash-Next on NVIDIA GPUs (RTX 30/40/50, 12+ GB VRAM; two or -# three cards can share one model, 8 GB each - docs/MULTI_GPU.md). +# Most people want the ready-made images instead (nothing compiled): docs/DOCKER.md. # -# The engine is compiled during docker build, so the first container start only -# downloads the model (~70 GB) and starts the server. docker build has no GPU, -# so the CUDA architectures are fixed here instead of read from nvidia-smi: the -# engine is a fat binary with a cubin per listed arch, and the runtime picks the -# one matching your card. Narrow CUDA_ARCHITECTURES to your card for a faster -# build; a card outside the set needs a rebuild with its own arch. +# docker build -t strata:src . # RTX 20/30/40/50 (compiles for each, ~25 min) +# docker build -t strata:src --build-arg CUDA_ARCHITECTURES=86 . # one card only (faster); 86 = RTX 30, 89 = RTX 40, 120 = RTX 50 +# docker build -t strata:src-cuda12 --build-arg CUDA_IMAGE=nvidia/cuda:12.9.1-devel-ubuntu24.04 \ +# --build-arg CUDA_ARCHITECTURES="60;61;70;75;80;86;89" --build-arg BUILD_VISION=0 . # GTX 10 / P100 / V100 (driver 575+) +# docker run --rm --gpus all -p 127.0.0.1:8080:8080 --ulimit memlock=-1 --shm-size 2g --stop-timeout 120 \ +# -v strata-data:/data -e MODEL=IQ3_XXS -e API_KEY=change-me-please-123 strata:src # -# Build: -# docker build -t strata . -# docker build -t strata --build-arg CUDA_ARCHITECTURES=89 . # RTX 40 only +# docker build has no GPU, so the CUDA architectures are given here instead of read from nvidia-smi. The engine is a fat binary with +# a machine-code part per listed architecture (plus PTX for the newest, which later cards can JIT), and the runtime picks the one +# matching your card. Narrow CUDA_ARCHITECTURES to your card for a faster build. Native code for the CPU that builds the image is NOT +# used (STRATA_PORTABLE=ON), so the image runs on any x86-64 CPU with AVX2. # -# Run (host needs an NVIDIA driver >= 580 and nvidia-container-toolkit): -# docker run --rm --gpus all \ -# -p 8080:8080 \ -# --ulimit memlock=-1 \ -# -v strata-data:/data \ -# -e MODEL=IQ2_XS \ -# strata -# -# Setup choices are env vars, read by docker-entrypoint.sh: FAMILY, MODEL, CONTEXT, -# VISION (no | yes | cpu), KV (int8 | q4_0 | k8v4), GPU (one card) or GPUS ("0,2" -# or "all", with LAYER_SPLIT), LOW_RAM (auto | on | off), HOST, PORT, API_KEY, -# GGUF_DIR (GGUF files you already have), RESIDENT_BUDGET_GIB, KV_STREAMING. -# -# Only the model files, the prepared pack, the MTP layer and the install config -# live in the /data volume; the engine is part of the image. Strata loads 32-62 GB -# into RAM, so a capped container needs -e LOW_RAM=on: setup.py reads the RAM from -# /proc/meminfo, which here is the host's total, not the container's limit. Add an -# API key before exposing the port to a network: -e API_KEY=. Pass -# -e REINSTALL=1 to change the model settings later. -# -# --gpus all on a host with two usable cards: setup takes both (the layer split is -# its recommended default). Pin one card with -e GPU=0, or name them with -# -e GPUS=0,2. A volume set up for one card switches to the pair on its first start -# on a two-card host unless GPU or GPUS pins it. LOW_RAM=on runs on one card. - -FROM nvidia/cuda:13.0.0-devel-ubuntu24.04 +# Plain legacy-builder features only (no heredocs, no --mount). AMD (HIP) and Intel (SYCL) source builds: docs/AMD_HIP.md, docs/INTEL.md. -# STRATA_EXECV=1: setup.py replaces itself with the server, so the server is PID 1 -# and docker stop's SIGTERM reaches it (see setup.start). Normal Linux starts, which -# don't set it, keep spawning the server as a child. -ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 LANG=C.UTF-8 STRATA_EXECV=1 +ARG CUDA_IMAGE=nvidia/cuda:13.0.0-devel-ubuntu24.04 +ARG RUNTIME_BASE=ubuntu:24.04 +# ---- 1. compile the engine and make its component package +FROM ${CUDA_IMAGE} AS engine-build +ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 PATH=/venv/bin:$PATH RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential ca-certificates curl git libatomic1 libgomp1 \ - python3 python3-pip python3-venv unzip \ + build-essential ca-certificates git libgomp1 libatomic1 python3 python3-pip python3-venv unzip \ && rm -rf /var/lib/apt/lists/* - -WORKDIR /opt/strata +WORKDIR /src COPY . . - -# RTX 20 (75), RTX 30 (86), RTX 40 (89), RTX 50 (120), plus 80 for A-series. CMakeLists -# refuses anything below 75. BUILD_VISION=0 skips the image encoder build. -ARG CUDA_ARCHITECTURES=75;80;86;89;120 +ARG CUDA_ARCHITECTURES="75;80;86;89;120" ARG BUILD_VISION=1 +ARG ENGINE_VERSION= +RUN python3 -m venv /venv && /venv/bin/pip install --no-cache-dir -r requirements.txt -r requirements-build.txt +# llama.cpp at the pinned commit (ggml for the engine, mtmd for pictures), exactly as setup.py fetches it +RUN /venv/bin/python -c "import setup; print(setup.get_llama_cpp())" +RUN set -e; \ + real=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do real="$real;${a}-real"; done; real=${real#;}; \ + last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \ + sm60=OFF; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do if [ "$a" -lt 75 ]; then sm60=ON; fi; done; \ + /venv/bin/cmake -G Ninja -S . -B build -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF \ + -DSTRATA_EXPERIMENTAL_SM60=$sm60 \ + -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_Q6K_EXPERTS=ON -DSTRATA_MMQ_KQUANTS=ON \ + "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual" -DSTRATA_GGML_DIR=/src/third_party/llama.cpp; \ + /venv/bin/cmake --build build --target strata strata_kq -j "$(nproc)"; \ + if [ "$BUILD_VISION" = "1" ]; then \ + /venv/bin/cmake -G Ninja -S tools/vision -B build-vision -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR=/src/third_party/llama.cpp \ + -DSTRATA_VISION_CUDA=ON -DSTRATA_PORTABLE=ON -DGGML_CUDA_NCCL=OFF "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual"; \ + /venv/bin/cmake --build build-vision --target strata-vision -j "$(nproc)"; \ + fi +RUN set -e; \ + mkdir -p /stage /engine; \ + cp build/strata /stage/; \ + [ -f build/libstrata_kq.so ] && cp build/libstrata_kq.so /stage/ || true; \ + [ -f build-vision/bin/strata-vision ] && cp build-vision/bin/strata-vision /stage/ || true; \ + ver="${ENGINE_VERSION:-$(sed -n 's/^[[:space:]]*project([^)]*VERSION[[:space:]]*\([0-9][0-9.]*\).*/\1/p' CMakeLists.txt | head -1)}"; \ + cudafull=$(nvcc --version | sed -n 's/.*release \([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -1); cudamajor=${cudafull%%.*}; \ + if [ "$cudamajor" = 13 ]; then mindriver=580.65; else mindriver=575.51; fi; \ + vision_archs=""; [ -f /stage/strata-vision ] && vision_archs=", \"vision_archs\": \"$CUDA_ARCHITECTURES\""; \ + echo "{\"version\": \"$ver\", \"source\": \"docker build\", \"archs\": \"$CUDA_ARCHITECTURES\", \"cuda\": \"$cudafull\", \"portable\": true${vision_archs}}" > /stage/BUILD.json; \ + python3 packaging/collect_libs.py --binary build/strata --search /usr/local/cuda/lib64 --out /stage --also 'libcublasLt.so*'; \ + archs=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do archs="$archs --arch sm_$a"; done; \ + last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \ + python3 packaging/package_engine.py --src /stage --backend cuda --version "$ver" --out /engine $archs --arch "compute_$last" \ + --min-driver nvidia=$mindriver --variant cuda$cudamajor --platform linux-x86_64 --build-id "docker-source-${ver}-cuda${cudafull}" --include SYSTEM-LIBS.txt --include 'libstrata_kq*' \ + --include strata-vision; \ + for d in /engine/*/; do python3 packaging/package_engine.py --verify "$d"; python3 packaging/binary_deps.py "$d"; done -RUN python3 -m venv .venv \ - && .venv/bin/pip install --no-cache-dir --upgrade pip \ - && .venv/bin/pip install --no-cache-dir -r requirements.txt \ - && chmod +x setup.sh docker-entrypoint.sh - -# llama.cpp at the pinned commit, then the engine and the image encoder, built -# exactly the way setup.py builds them: native code for the CPU that builds the -# image, so build it on the PC it runs on. BUILD.json is what setup.py reads to -# decide whether an engine is current: source=local with a matching src hash -# means the first start reuses it instead of recompiling. -RUN .venv/bin/python - <<'PYEOF' -import json, os, pathlib, shutil -import setup - -llama = setup.get_llama_cpp() -nvcc, _ = setup.find_nvcc() -arch = os.environ.get("CUDA_ARCHITECTURES", "75;80;86;89;120").strip().strip('"').replace(",", ";") -vision = "gpu" if os.environ.get("BUILD_VISION", "1") == "1" else "none" - -setup.cmake_build(setup.ROOT, setup.ROOT / "build", "strata", - ["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_Q6K_EXPERTS=ON", "-DSTRATA_MMQ_KQUANTS=ON", "-DSTRATA_BUILD_TESTS=OFF", - f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}", - f"-DSTRATA_GGML_DIR={llama}"], None, "build-strata.bat") -if vision != "none": - setup.cmake_build(setup.ROOT / "tools" / "vision", setup.ROOT / "build-vision", "strata-vision", - [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=ON", "-DSTRATA_PORTABLE=OFF", - f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}"], None, "build-vision.bat") - -eng = setup.ROOT / "engine" -eng.mkdir(exist_ok=True) -shutil.copy2(setup.ROOT / "build" / setup.EXE, eng / setup.EXE) -if (setup.ROOT / "build" / setup.KQ_LIB).exists(): # the K-quant MMQ prompt library (UD-Q4/Q5/Q6_K_XL files) - shutil.copy2(setup.ROOT / "build" / setup.KQ_LIB, eng / setup.KQ_LIB) -if vision != "none": - shutil.copy2(setup.ROOT / "build-vision" / "bin" / setup.VEXE, eng / setup.VEXE) -bindir = pathlib.Path(nvcc).parent -meta = {"source": "local", "version": setup.source_version(), - "archs": [int(a.split("-")[0]) for a in arch.split(";") if a.split("-")[0].isdigit()], "vision": vision, - "cuda_dirs": [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()], - "src": setup.source_hash(setup.ENGINE_SOURCES), - "vision_src": setup.source_hash(setup.VISION_SOURCES) if vision != "none" else None} -(eng / "BUILD.json").write_text(json.dumps(meta, indent=1)) -PYEOF - -# the cmake trees are build-time only; the engine itself is what the container needs -RUN rm -rf build build-vision +# ---- 2. the Terminal (the release archive, built here) +FROM ${RUNTIME_BASE} AS terminal +ARG STRATA_COMMIT= +ENV STRATA_BUILD_COMMIT=${STRATA_COMMIT} +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends python3 ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY . /src/ +RUN python3 /src/packaging/package_terminal.py --out /out --cache /cache \ + && mkdir -p /opt/strata \ + && tar -xzf /out/strata-terminal-*-linux-x86_64.tar.gz -C /opt/strata \ + && mv /opt/strata/strata-terminal-* /opt/strata/terminal \ + && /opt/strata/terminal/bin/strata --version +# llama.cpp at the commit setup.py pins: fetched here, so the first start does not depend on GitHub. Only gguf-py (the model preparation +# tools) and the file setup.py looks for (ggml/CMakeLists.txt) are kept: 170 MB become a few +RUN cd /opt/strata/terminal && STRATA_CONTROL_INSTALL=1 STRATA_INSTALL_DIR=/opt/strata/seed PYTHONNOUSERSITE=1 \ + /opt/strata/terminal/python/bin/python3 -c "import setup; print(setup.get_llama_cpp())" \ + && rm -rf /opt/strata/seed/third_party/*.zip* \ + && cd /opt/strata/seed/third_party/llama.cpp \ + && find . -mindepth 1 -maxdepth 1 ! -name gguf-py ! -name ggml ! -name 'LICENSE*' -exec rm -rf {} + \ + && find ggml -mindepth 1 -depth ! -type d ! -name CMakeLists.txt -delete && find ggml -mindepth 1 -type d -empty -delete \ + && du -sh /opt/strata/seed +# ---- 3. the runtime image (the same as docker/Dockerfile's, FLAVOR=cuda) +FROM ${RUNTIME_BASE} +ARG STRATA_VERSION=dev +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends tini ca-certificates libgomp1 libatomic1 libnuma1 zlib1g \ + && rm -rf /var/lib/apt/lists/* /var/cache/apt/* +COPY --from=terminal /opt/strata/terminal /opt/strata/terminal +COPY --from=terminal /opt/strata/seed /opt/strata/seed +COPY --from=engine-build /engine/ /opt/strata/components/engine/ +COPY docker/entrypoint.sh docker/healthcheck.sh /opt/strata/ +COPY docker/strata-wrapper.sh /usr/local/bin/strata +RUN chmod 0755 /opt/strata/entrypoint.sh /opt/strata/healthcheck.sh /usr/local/bin/strata +ENV STRATA_COMPONENTS_DIR=/opt/strata/components STRATA_INSTALL_DIR=/data/install XDG_STATE_HOME=/data/state \ + XDG_CONFIG_HOME=/data/config HOME=/data/home PORT=8080 LANG=C.UTF-8 PYTHONUNBUFFERED=1 PYTHONNOUSERSITE=1 STRATA_IN_DOCKER=1 \ + NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utility VOLUME ["/data"] EXPOSE 8080 - -# /health is answered before the API key gate, so it works with or without one. -# The port only opens after the model loads (1-3 minutes, longer on a first run), -# so the start period is generous: a too short one marks a still-loading container -# unhealthy and a restart policy would kill it mid-download. -HEALTHCHECK --interval=30s --timeout=5s --start-period=600s --retries=3 \ - CMD curl -fs "http://127.0.0.1:${PORT:-8080}/health" || exit 1 - -ENTRYPOINT ["./docker-entrypoint.sh"] +LABEL org.opencontainers.image.title="Strata" com.strata.flavor="cuda" com.strata.build="from-source" org.opencontainers.image.version="${STRATA_VERSION}" +HEALTHCHECK --interval=30s --timeout=8s --start-period=2h --retries=3 CMD ["/opt/strata/healthcheck.sh"] +STOPSIGNAL SIGTERM +ENTRYPOINT ["/usr/bin/tini", "--", "/opt/strata/entrypoint.sh"] +CMD ["run"] diff --git a/README.de.md b/README.de.md index 43ee23e513f..9769c995f97 100644 --- a/README.de.md +++ b/README.de.md @@ -1,239 +1,188 @@ -

Strata

+

+ + + Strata + +

-[English](README.md) · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · **Deutsch** · [Français](README.fr.md) · [Español](README.es.md) · [Português](README.pt-BR.md) +

Leistungsstarke KI auf deinem eigenen Computer.

+

Chatten, programmieren und mit Bildern arbeiten, lokal.

-

Ein KI-Modell mit 125 Milliarden Parametern auf deinem eigenen Gaming-PC
-NVIDIA- oder AMD-Grafikkarte (ab 12 GB) · Windows oder Linux · kostenlos und Open Source

+

+ Modelle · Installation · + Hardware · Tools · + Hilfe · Unterstützen +

-

Ein Voxel-Pagodengarten, den das Modell in Strata geschrieben hat, läuft im Browser
-Ein Voxel-Pagodengarten aus einem einzigen Prompt, auf einer RTX 5070 mit Strata (IQ3_S, 128K Kontext) · -ganzes Video (49 s)

+

+ Strata herunterladen + MIT-Lizenz + Strata auf Buy Me a Coffee unterstützen +

-Strata lässt **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** auf einem normalen PC laufen. -Das ist ein großes, kluges KI-Modell, das sonst meist einen Server braucht. Es chattet, schreibt Code, versteht -Bilder und arbeitet mit deinen Apps und Coding-Agents zusammen. Nichts verlässt deinen PC. +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

-## Wie schnell ist es? +**Kostenlos, Open Source und ganz in deiner Hand.** Nutze Strata auf dem Desktop oder mit deinen liebsten Coding-Tools. Kein Konto nötig. -Wir haben es auf zwei ganz normalen Gaming-PCs gemessen. Ein Token ist etwa ¾ eines Wortes. +## Modelle -- **Schreibt Antworten:** wie schnell die Antwort in einem kurzen Chat erscheint. 60 Tokens pro Sekunde sind - schneller, als du lesen kannst. -- **Liest deinen Prompt:** wie schnell es aufnimmt, was du schickst (hier ein Dokument, Code oder Chatverlauf mit - 32K Tokens). +Wir empfehlen **zuerst ISTA-DASLab**, danach **Unsloth** und andere Anbieter, soweit ein passendes Modell in deinen Speicher passt. - - - -
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM
+
+  Qwen3.8-Flash-Next -| Größe | Schreibt Antworten | Liest deinen Prompt | +| Anbieter | Auswahl | +| --- | --- | +| **ISTA-DASLab · empfohlen** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) zum Programmieren. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Geringerer Speicherbedarf, aber langsamer. | +| **Weitere Optionen** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Größen, Speicherbedarf und Kompatibilität vergleichen](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Das sind die derzeit dokumentierten Pakete für dieses Modell. + +[Modellanleitung und Kompatibilität](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +In der **Desktop-App** und im **Terminal**. Was nicht in den Arbeitsspeicher passt, wird von deiner SSD gelesen. Darum brauchst du viel freien Speicherplatz. + +| Set (ISTA-DAS) | Download | Freier Speicherplatz nötig | | --- | ---: | ---: | -| **Q2_0** | 94 Tokens/s | 2,650 Tokens/s | -| **IQ2_XS** | 79 Tokens/s | 2,090 Tokens/s | -| **IQ3_XXS** | 62 Tokens/s | 1,750 Tokens/s | -| **IQ3_S** | 53 Tokens/s | 1,620 Tokens/s | -| **Coder** | 55 Tokens/s | 2,180 Tokens/s | +| 1.75 bpw | 239 GB | etwa 245 GB | +| 2.00 bpw | 257 GB | etwa 265 GB | +| 2.25 bpw | 274 GB | etwa 280 GB | -
+Läuft auf NVIDIA RTX 30, 40 und 50 (Windows und Linux) und auf AMD Radeon AI PRO R9700 (Linux). Das Setup lädt die Dateien und die DeepSeek-Engine herunter und startet dann das Modell. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` -| Größe | Schreibt Antworten | Liest deinen Prompt | +Gemessen mit dem 2.00-bpw-Set auf Strata 0.2.5. „Ausgabe“ ist das Tempo der Antwort, „Prompt“ zeigt, wie schnell Strata deine Eingabe liest. + +| Hardware | Ausgabe | Prompt | | --- | ---: | ---: | -| **Q2_0** | 60 Tokens/s | 1,160 Tokens/s | -| **IQ2_XS** | 52 Tokens/s | 1,110 Tokens/s | -| **Coder** | 44 Tokens/s | 1,420 Tokens/s | +| RTX 5070 12 GB, 64 GB RAM | 4 bis 6 Token/s | etwa 110 Token/s (4K) | +| RTX 3060 12 GB, 46 GB RAM | 9 bis 11 Token/s | etwa 155 Token/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB RAM | 21 bis 25 Token/s | 320 bis 360 Token/s (8K) | +| 4x Radeon AI PRO R9700 | 74 bis 77 Token/s | 400 bis 450 Token/s (8K) | -
+[Speicher, Festplatte und Details](docs/DEEPSEEK41.md) · [Versionshinweise](https://github.com/Niko1221/Strata/releases) -NVIDIA: Q2_0 mit Engine 0.1.36, die anderen Zeilen mit 0.1.26 (4K Antworten, 32K Prompts). Die vollständigen -Tabellen stehen in [DETAILS.md](docs/DETAILS.md#speed-measured). Eine Karte mit mehr VRAM ist schneller: Eine -RTX 3090 (24 GB) sollte etwa 100-140 Tokens pro Sekunde schreiben. Lange Chats und andere Karten: -[Tempo jedes Modells](docs/MODELS.md#how-fast-is-each-size), [Ergebnisse aus der Community](docs/COMMUNITY_BENCHMARKS.md). + -

Buy Me A Coffee
-Strata ist kostenlos. Wenn es auf deinem PC gut läuft, hält ein Kaffee die Arbeit daran am Laufen.

+ -## Was du brauchst +Unsicher, was passt? [Wähle ein Modell für deinen Computer](docs/MODELS.md#pick-by-memory). -| | | -| --- | --- | -| **Grafikkarte** | **NVIDIA** GeForce RTX 20, 30, 40 oder 50 Serie, oder **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 oder RX 6800 / 6900 Serie. Sie braucht **12 GB VRAM oder mehr**. | -| **RAM** | 32 GB oder mehr. Dein RAM entscheidet, [welches Modell](#welches-modell-soll-ich-nehmen) passt. Mit 64 GB laufen alle Größen. | -| **Festplatte** | Etwa 80 GB frei. Nimm wenn möglich eine SSD: Der erste Start geht dann viel schneller. | -| **System** | Windows 10 / 11 oder Linux und ein aktueller Grafiktreiber von NVIDIA oder AMD. | +## Installation + + -Alles andere richtet der Installer ein. Zwei oder drei Karten können sich das Modell teilen ([Multi-GPU](docs/MULTI_GPU.md)). +### Desktop-App -Experimentell, von Community-Mitgliedern auf ihren eigenen Rechnern geschrieben und getestet: +**[Strata für Windows, Linux oder Mac herunterladen →](https://github.com/Niko1221/Strata/releases/latest)** -- **Ältere Grafikkarten** (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT): [Ältere GPUs](docs/OLDER_GPUS.md). -- **Intel Arc**, unter Linux aus dem Quellcode gebaut: [Intel Arc](docs/INTEL_ARC.md). -- **AMD Ryzen AI Max (Strix Halo)**, unter Linux aus dem Quellcode gebaut: [Strix Halo](docs/STRIX_HALO.md). -- **Ältere Prozessoren ohne AVX2**: Sie funktionieren, aber langsam. [Ältere CPUs](docs/INSTALL.md#older-cpus-experimental). +Installiere die App, wähle ein Modell und leg mit dem Chat los. Es gibt einen Installer pro System. Beim ersten Start lädt die App die Engine für deine Grafikkarte herunter. [Hilfe zum Installer](docs/INSTALL.md#the-app). -Die vollständige Liste: [docs/INSTALL.md](docs/INSTALL.md#what-you-need). +Dateien: `Strata-0.2.9-windows-x64-setup.exe` · `Strata-0.2.9-linux-x86_64.AppImage` · `Strata-0.2.9-macos-arm64.dmg` -## Installieren +

+ Strata-Desktop-App mit Chat und Live-Codevorschau nebeneinander +
Chat, Dateien und Live-Vorschau in einem Fenster. +

-### Lass deine KI es einrichten + -Nutzt du einen KI-Coding-Assistenten (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Füge dort diesen Text ein: +### Terminal-App -```text -Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +Lieber im Terminal? Installiere Strata und starte dann **`strata launch`**. + +
+Installationsbefehle + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh ``` -Er prüft deine Grafikkarte, deinen RAM und deine Festplatte und wählt das passende Modell. Dann installiert und -startet er es und sagt dir, wie du deine Apps verbindest. KI-Tools können Strata auch über seinen -[MCP-Server](docs/MCP_SERVER.md) installieren, starten und stoppen. - -### Oder mach es selbst - -[Lade Strata herunter](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) und entpacke es (oder nutze -`git clone`). **Windows:** Doppelklick auf **`START-HERE.bat`**. **Linux:** Führe im Strata-Ordner **`./setup.sh`** aus. - -**Mac (Apple Silicon, M1 bis M5, macOS 15 oder neuer):** Installiere einmal Apples Command Line Tools (`xcode-select --install` im Terminal; Xcode selbst brauchst du nicht). Öffne dann das Terminal im Strata-Ordner und führe **`./setup.sh`** aus. Es baut die Mac-Engine auf deinem Mac (etwa 7 Minuten), stellt dieselben Fragen, lädt das Modell und startet es. Beim nächsten Mal startet `./setup.sh` sofort. Welche Größe zu deinem Mac passt und wie schnell es ist: [docs/MAC.md](docs/MAC.md). - -Die Schritte sind für NVIDIA und AMD gleich. Der Installer erkennt deine Karte und richtet die passende Engine -dafür ein. Er stellt dir ein paar Fragen: - -- welches Modell und welche Größe, -- wie viel Kontext (wie viel Text sich das Modell merkt), -- ob es Bilder lesen soll. - -Drück jedes Mal Enter, um die empfohlene Antwort zu nehmen. Dann lädt er das Modell herunter (etwa 70 GB) und -startet es. Bricht der Download ab, starte ihn einfach neu: Er macht dort weiter, wo er aufgehört hat. Dein Browser -öffnet die Strata-App unter `http://127.0.0.1:8080`. - -> **Während das Modell startet, kann dein PC 1-3 Minuten langsam sein oder nicht reagieren** (beim ersten Mal am -> längsten). Strata lädt 35-55 GB in deinen RAM und reserviert einen Teil davon für die Grafikkarte. Das ist normal. -> Warte und schließ das Fenster nicht. Im Fenster siehst du, was Strata gerade tut. - -**Beim nächsten Mal** startest du wieder `START-HERE.bat` (oder `./setup.sh`). Es startet sofort und lädt nichts -doppelt herunter. Schließ das Fenster, um das Modell zu stoppen. `UPDATE.bat` (`./update.sh`) aktualisiert Strata, -ohne es zu starten. Updates, Docker, mehrere Karten, wo die Dateien landen und alle Optionen: -[docs/INSTALL.md](docs/INSTALL.md). - -## Welches Modell soll ich nehmen? - -Der Installer empfiehlt eins passend zu deinem RAM. Dasselbe Modell gibt es in mehreren Größen, mehr oder weniger -stark komprimiert. Kleinere Größen sind schneller. Größere sind etwas klüger. - -| Dein RAM | Nimm | Warum | -| --- | --- | --- | -| **32 GB** | **Coder** | passt in 32 GB und ist für Code gemacht (mit einer 24-GB-Karte laufen auch Q2_0 und IQ2_XS) | -| **48 GB** | **IQ2_XS** (oder Q2_0, das schnellste) | die größeren Größen passen nicht | -| **64 GB** | **IQ2_XS** (empfohlen) oder IQ3_XXS / IQ3_S | alle Größen passen; IQ3_S ist das beste und das langsamste | -| **96 GB oder mehr** | **IQ3_S** oder Unsloths UD-IQ4_XS (~4 Bit) | Platz für die größten Größen, auch wenn alles andere offen ist | - -- **[Coder](docs/MODELS.md#coder):** eine Version für Code, bei der die Hälfte der Experten entfernt wurde. Sie - erreicht 91 % des SWE-bench-Verified-Werts des vollen Modells (von ihren Autoren gemessen) und passt in 32 GB RAM. - Außerhalb von Code ist sie schwächer, auch bei chinesischem und anderem CJK-Text (#438). Nimm dafür Q2_0, IQ2_XS - oder IQ3_S, die alle Experten behalten. -- **[Swift 1.5](docs/MODELS.md#swift-15):** ein Fine-Tune, das viel kürzer nachdenkt, bevor es antwortet. Du - bekommst die Antwort früher, bei etwa gleicher Qualität. -- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** die ~4-Bit-Version von Unsloth, in der Qualität - zwischen IQ3_S und UD-Q4_K_XL. 94 GB Download. Mit weniger als ~80 GB RAM liest Strata einen Teil davon während - der Antwort von der SSD, dort ist es also langsamer (eine NVMe-SSD hilft). -- **[Unsloth UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL und Q8_0](docs/MODELS.md#unsloths-files-ud-iq4_xs-to-q8_0):** 4 bis 8 Bit, näher am vollen Modell - (93-95 % das gleiche nächste Token wie Q8_0). Schnell, wenn alle Experten in den RAM passen (~88 GB für UD-Q4_K_XL - bis ~136 GB für Q8_0); mit weniger RAM liest Strata einen Teil davon während der Antwort von der SSD, was viel - langsamer ist (7-8.5 Tokens/s für UD-Q4_K_XL auf einem PC mit 64 GB). -- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** Das richtest du von Hand - ein. Es steht nicht im Menü des Installers. - -Größen, Downloads und was wohin passt: [docs/MODELS.md](docs/MODELS.md). Um später ein weiteres Modell -hinzuzufügen, starte `SETUP.bat` (Linux: `./setup.sh --setup`). - -## So benutzt du es - -

Der Monitor-Tab der Strata-App neben einem Coding-Agent
-Der Monitor der Strata-App (links), während ein Coding-Agent den Pagodengarten aus dem Video schreibt (rechts)

- -- **Im Browser:** Öffne `http://127.0.0.1:8080`. Dort gibt es **Chat**, einen Live-**Monitor** für das Modell und - deine GPU/CPU/RAM und **About** mit den Einstellungen und Adressen. -- **Deine Apps und Coding-Agents:** Füge einen „OpenAI-kompatiblen“ Anbieter mit der Basis-URL - **`http://127.0.0.1:8080/v1`** hinzu. Jeder API-Key und jeder Modellname funktioniert. - - Apps, die die API von Anthropic nutzen: `http://127.0.0.1:8080/v1/messages` (Claude Code: - `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). - - Codex CLI und andere Apps, die die OpenAI Responses API nutzen: `/v1/responses` - ([Einrichtung](docs/DETAILS.md#the-responses-api-and-codex-cli)). -- **Nachdenken:** Wähle **aus, niedrig, mittel oder hoch** im Chat-Menü oder unter „Reasoning Effort“ in deiner - App. Aus ist am schnellsten. Hoch ist am besten für schwierige Fragen. -- **Bilder:** Antworte im Setup mit Ja auf „Images?“. Klick dann im Chat auf **Picture** oder hänge Bilder in deiner - App an. AMD-Karten lesen Bilder unter Linux über den Prozessor; unter Windows geht das noch nicht. -- **Vom Handy oder einem anderen PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `. Setz immer einen - Key. -- **Eine Anfrage nach der anderen:** Standardmäßig beantwortet Strata eine Anfrage, die anderen warten. Um mehrere - gleichzeitig zu beantworten, setz `"parallel": 2` ([BATCHING.md](docs/BATCHING.md)). Auf einer 12-GB-Karte wird - dadurch jede Antwort langsamer. -- **Lange Prompts:** Strata liest die erste Nachricht eines Chats komplett, etwa 1 Minute pro 30,000 Tokens. - Folgenachrichten starten in Sekunden. - -Mehr: [wo deine Chats gespeichert werden](docs/INSTALL.md#where-things-are-stored), [die API](docs/DETAILS.md#using-it). - -### Optional: mehr Tempo mit einer Grafikkarte, wenn das ganze Modell in den RAM passt - -Zwei Opt-in-Einstellungen (von RubenTorney, #1904 und #1905). Sie helfen, wenn du eine Grafikkarte nutzt und dein RAM alle Experten hält (Stratas Arena-Modus, zum Beispiel Q2_0 oder IQ3_XXS auf einem PC mit 64 GB). Öffne deine Konfiguration `strata-.json` im Strata-Datenordner ([wo](docs/INSTALL.md#where-things-are-stored)) und füge hinzu: - -- **Schnellere Ausgabe:** `"--adapt-async", "1"` in die Liste `"args"`. Der Experten-Cache wird dann in einem Hilfs-Thread aktualisiert, statt die Antwort anzuhalten. Gemessen auf einer RTX 5070 (Windows, Q2_0): +4-5 % Ausgabe, +7-10 % bei Code und langen Dokumenten. Antworten können leicht vom Standard abweichen (sie bleiben von Lauf zu Lauf gleich). -- **Schnelleres Prompt-Lesen unter Windows:** `"STRATA_PIN_BY_NEED": "1"` im Block `"env"`. Windows kann nur etwa den halben RAM für die Grafikkarte sperren; damit werden zuerst die Experten gesperrt, die die Karte wirklich braucht. Gemessen auf der RTX 5070: +4,4 % Prompt-Lesen. - -```json -"args": [ ..., "--adapt-async", "1" ], -"env": { "STRATA_PIN_BY_NEED": "1" } +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +Öffne unter Windows danach ein neues Terminal. Dann: + +```sh +strata launch ``` -Starte Strata danach neu (`START-HERE.bat` oder `./setup.sh`). Zum Rückgängigmachen entferne die beiden Einträge. +Folge den Anweisungen, um ein Modell herunterzuladen und zu starten. [Terminal-Anleitung](docs/TERMINAL_LAUNCH.md). -## Etwas ist schiefgelaufen? +
-- **Mein PC ist beim ersten Start von Strata eingefroren.** Das ist normal, während das Modell lädt. Warte und - schließ das Fenster nicht. Nach 10 Minuten immer noch eingefroren? Starte den PC neu, schließ andere Programme und - versuch es noch einmal, oder nimm eine kleinere Größe. -- **Es hat beim Herunterladen oder Installieren aufgehört.** Starte `START-HERE.bat` (oder `./setup.sh`) noch - einmal. Es macht dort weiter, wo es aufgehört hat. -- **Es ist sehr langsam und die Festplattenlampe blinkt ständig, oder es meldet „the engine stopped - unexpectedly“.** Dein PC hat nicht genug freien RAM. Schließ andere Programme (Browser brauchen viel) oder nimm - eine kleinere Größe (Q2_0 oder IQ2_XS). -- **Es meldet, dass Port 8080 schon belegt ist.** Strata läuft bereits. Such nach seinem Fenster. +

+ Strata-Terminal-App mit Modellaktivität, Tempo, Speicher und letzten Anfragen +
Behalte Modell und Hardware im Blick, während es läuft. +

-Weitere Probleme und ihre Lösungen: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Kommst du nicht weiter? -Öffne ein [Issue](https://github.com/Niko1221/Strata/issues) und hänge `strata-.log` aus dem Strata-Ordner -an. Du hast ein Sicherheitsproblem gefunden? Melde es vertraulich: [SECURITY.md](SECURITY.md). + -## Wie funktioniert es? +[Aus dem Quellcode bauen](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Vollständige Installationsanleitung](docs/INSTALL.md) -Modelle wie dieses laufen normalerweise auf Servern mit Hunderten Gigabyte Grafikspeicher. Deine Grafikkarte hat -12-24 GB. Strata bringt das Modell trotzdem unter, indem es **die Arbeit auf deinen ganzen PC verteilt**. Stell dir -eine Küche vor: Was du ständig brauchst, bleibt auf der Arbeitsfläche, der Rest wartet in der Vorratskammer. + -

Die 24,576 Experten des Modells: die meistgenutzten auf der Grafikkarte, alle im RAM, eine Nachschlagetabelle auf der SSD

+## Hardware -- **Das Modell ist ein Team aus 24,576 kleinen Spezialisten („Experten“).** Jedes Wort braucht nur 10 davon. -- **Deine Grafikkarte** hält die paar tausend Experten, die am häufigsten gebraucht werden. **Dein RAM** hält alle, - und **dein Prozessor** rechnet gleichzeitig am Rest. **Deine SSD** hält eine große Nachschlagetabelle. +| Unterstützte Hardware | Anleitung | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [NVIDIA-Setup](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [AMD-Setup](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · experimentell** | [RX-6000-Setup](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Intel-Setup](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 oder neuer** | [Mac-Setup](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Strix-Halo-Setup](docs/STRIX_HALO.md) | + + -

Ein kleiner Helfer rät die nächsten Wörter; das große Modell prüft alle auf einmal und behält die richtigen

+## Tools -- **Raten, dann prüfen:** Ein kleiner Helfer rät die nächsten paar Wörter. Das große Modell prüft sie alle auf - einmal. Du bekommst dieselbe Antwort, nur 1.6-1.8x schneller. -- **Lange Texte werden in großen Stücken gelesen** (bis zu 8,192 Tokens auf einmal), mit über 1,000 Tokens pro - Sekunde. +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, und weitere über die OpenAI- und Anthropic-kompatiblen APIs. -Die längere Erklärung: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Jeder Teil und seine Zahlen: -[die Details](docs/DETAILS.md#how-it-works) und das [Paper](docs/paper/Strata-Paper.pdf). +Führe **`strata connect`** aus, um die Einrichtung für dein Tool zu sehen. [Verbindungsanleitung](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). -## Danksagung und Lizenz + + + + -Das Modell ist [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) vom Qwen-Team. Komprimiert -wurde es von [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) -und Unsloth. Strata nutzt Teile von [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). Alle Danksagungen: -[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata ist Open Source unter der [MIT-Lizenz](LICENSE). Ein -paar Teile und alle Modelle haben eigene Lizenzen ([welche](docs/HOW_IT_WORKS.md#license)). +## Hilfe + +[Alle Anleitungen](docs) · [Fehlerbehebung](docs/TROUBLESHOOTING.md) · [Fehler melden](https://github.com/Niko1221/Strata/issues/new/choose) · +[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [So funktioniert es](docs/HOW_IT_WORKS.md) · [Mitmachen](CONTRIBUTING.md) ## Strata unterstützen -Strata ist kostenlos und Open Source. Wenn es dir nützt, kannst du die Entwicklung unterstützen: +**Hilf mit, lokale KI für alle offen zu halten.** Ein Kaffee hilft, Entwicklung und Tests auf mehr Hardware zu finanzieren. + +Buy Me a Coffee: Strata unterstützen + +[MIT-Lizenz](LICENSE) · [Danksagung und Modelllizenzen](docs/HOW_IT_WORKS.md#credits) · [Datenschutz](docs/SAFETY.md) + + + +Für KI-Tools und automatische Leser: technische Referenz · Setup-Anleitung. -

Buy Me A Coffee

+**Sponsoring, Hardware-Partnerschaften oder Zusammenarbeit:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/README.es.md b/README.es.md index 5e345c37f13..fe35e83af20 100644 --- a/README.es.md +++ b/README.es.md @@ -1,233 +1,188 @@ -

Strata

+

+ + + Strata + +

-[English](README.md) · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · **Español** · [Português](README.pt-BR.md) +

IA potente en tu propio ordenador.

+

Chatea, programa y trabaja con imágenes, en local.

-

Ejecuta un modelo de IA de 125 mil millones de parámetros en tu propio PC gaming
-Tarjeta gráfica NVIDIA o AMD (12 GB o más) · Windows o Linux · libre y de código abierto

+

+ Modelos · Instalación · + Hardware · Herramientas · + Ayuda · Apoyar +

-

Un jardín con una pagoda de vóxeles que escribió el modelo de Strata, funcionando en el navegador
-Un jardín con una pagoda de vóxeles, hecho con un solo prompt en una RTX 5070 con Strata (IQ3_S, contexto de 128K) · -vídeo completo (49 s)

+

+ Descargar Strata + Licencia MIT + Apoya Strata en Buy Me a Coffee +

-Strata ejecuta **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** en un PC normal. Es un -modelo de IA grande e inteligente que normalmente necesita un servidor. Conversa, escribe código, entiende imágenes -y funciona con tus aplicaciones y agentes de programación. Nada sale de tu PC. +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

-## ¿Qué velocidad tiene? +**Gratis, de código abierto y tuyo para ejecutar.** Usa Strata en tu escritorio o con tus herramientas de programación favoritas. No necesitas cuenta. -Lo medimos en dos PC gaming normales. Un token equivale más o menos a ¾ de una palabra. +## Modelos -- **Escribe respuestas:** lo rápido que aparece la respuesta en un chat corto. 60 tokens por segundo es más rápido de lo que puedes leer. -- **Lee tu prompt:** lo rápido que procesa lo que le envías (aquí, un documento, código o historial de chat de 32K tokens). +Recomendamos **primero ISTA-DASLab**, después **Unsloth** y otros proveedores, siempre que haya un modelo compatible que quepa en tu memoria. - - - -
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM
+
+  Qwen3.8-Flash-Next -| Tamaño | Escribe respuestas | Lee tu prompt | +| Proveedor | Opciones | +| --- | --- | +| **ISTA-DASLab · recomendado** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) para programar. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Usa menos memoria, pero es más lento. | +| **Otras opciones** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Compara tamaños, necesidades de memoria y compatibilidad](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Son los paquetes documentados actualmente para este modelo. + +[Guía del modelo y compatibilidad](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +En la **aplicación de escritorio** y en el **Terminal**. Lo que no cabe en la memoria se lee desde tu SSD, así que hace falta mucho espacio libre en disco. + +| Conjunto (ISTA-DAS) | Descarga | Espacio libre necesario | | --- | ---: | ---: | -| **Q2_0** | 94 tokens/s | 2,650 tokens/s | -| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | -| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | -| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | -| **Coder** | 55 tokens/s | 2,180 tokens/s | +| 1.75 bpw | 239 GB | unos 245 GB | +| 2.00 bpw | 257 GB | unos 265 GB | +| 2.25 bpw | 274 GB | unos 280 GB | + +Funciona en NVIDIA RTX 30, 40 y 50 (Windows y Linux) y en AMD Radeon AI PRO R9700 (Linux). La instalación descarga los archivos y el motor de DeepSeek, y después inicia el modelo. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` -
+Medido con el conjunto de 2.00 bpw en Strata 0.2.5. «Salida» es la velocidad de la respuesta; «Prompt» es la rapidez con la que Strata lee tu texto. -| Tamaño | Escribe respuestas | Lee tu prompt | +| Hardware | Salida | Prompt | | --- | ---: | ---: | -| **Q2_0** | 60 tokens/s | 1,160 tokens/s | -| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | -| **Coder** | 44 tokens/s | 1,420 tokens/s | +| RTX 5070 12 GB, 64 GB de RAM | 4 a 6 tokens/s | unos 110 tokens/s (4K) | +| RTX 3060 12 GB, 46 GB de RAM | 9 a 11 tokens/s | unos 155 tokens/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 a 25 tokens/s | 320 a 360 tokens/s (8K) | +| 4x Radeon AI PRO R9700 | 74 a 77 tokens/s | 400 a 450 tokens/s (8K) | -
+[Memoria, disco y detalles](docs/DEEPSEEK41.md) · [Notas de la versión](https://github.com/Niko1221/Strata/releases) -NVIDIA: Q2_0 con el motor 0.1.36, las demás filas con 0.1.26 (respuestas de 4K, prompts de 32K). Las tablas -completas están en [DETAILS.md](docs/DETAILS.md#speed-measured). Una tarjeta con más VRAM es más rápida: una -RTX 3090 (24 GB) debería escribir unos 100-140 tokens por segundo. Chats largos y otras tarjetas: -[velocidad de cada modelo](docs/MODELS.md#how-fast-is-each-size), [resultados de la comunidad](docs/COMMUNITY_BENCHMARKS.md). + -

Buy Me A Coffee
-Strata es gratis. Si funciona bien en tu PC, un café ayuda a seguir trabajando en él.

+ -## Qué necesitas +¿No sabes qué cabe? [Elige un modelo para tu ordenador](docs/MODELS.md#pick-by-memory). -| | | -| --- | --- | -| **Tarjeta gráfica** | **NVIDIA** GeForce serie RTX 20, 30, 40 o 50, o **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 o serie RX 6800 / 6900. Necesita **12 GB de VRAM o más**. | -| **RAM** | 32 GB o más. Tu RAM decide [qué modelo](#qué-modelo-elijo) cabe. Con 64 GB funcionan todos los tamaños. | -| **Disco** | Unos 80 GB libres. Usa un SSD si puedes: el primer arranque es mucho más rápido. | -| **Sistema** | Windows 10 / 11 o Linux, y un controlador gráfico actual de NVIDIA o AMD. | +## Instalación -El instalador prepara todo lo demás. Dos o tres tarjetas pueden repartirse el modelo ([multi-GPU](docs/MULTI_GPU.md)). + -Experimental, escrito y probado por miembros de la comunidad en sus propios equipos: +### Aplicación de escritorio -- **Tarjetas gráficas antiguas** (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT): [Older GPUs](docs/OLDER_GPUS.md). -- **Intel Arc**, compilado desde el código fuente en Linux: [Intel Arc](docs/INTEL_ARC.md). -- **AMD Ryzen AI Max (Strix Halo)**, compilado desde el código fuente en Linux: [Strix Halo](docs/STRIX_HALO.md). -- **Procesadores antiguos sin AVX2**: funcionan, pero despacio. [Older CPUs](docs/INSTALL.md#older-cpus-experimental). +**[Descargar Strata para Windows, Linux o Mac →](https://github.com/Niko1221/Strata/releases/latest)** -La lista completa: [docs/INSTALL.md](docs/INSTALL.md#what-you-need). +Instala la aplicación, elige un modelo y empieza a chatear. Hay un instalador por sistema. En el primer arranque, la aplicación descarga el motor para tu tarjeta gráfica. [Ayuda con el instalador](docs/INSTALL.md#the-app). -## Instalación +Archivos: `Strata-0.2.9-windows-x64-setup.exe` · `Strata-0.2.9-linux-x86_64.AppImage` · `Strata-0.2.9-macos-arm64.dmg` -### Deja que tu IA lo instale +

+ Aplicación de escritorio de Strata con un chat y una vista previa del código en vivo, una junto a otra +
Chat, archivos y vista previa en vivo en una sola ventana. +

-¿Usas un asistente de programación con IA (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Pega esto en él: + -```text -Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +### Aplicación de Terminal + +¿Prefieres la terminal? Instala Strata y ejecuta **`strata launch`**. + +
+Comandos de instalación + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh ``` -Revisa tu tarjeta gráfica, tu RAM y tu disco, y elige el modelo que cabe. Luego lo instala, lo arranca y te explica -cómo conectar tus aplicaciones. Las herramientas de IA también pueden instalar, arrancar y detener Strata con su -[servidor MCP](docs/MCP_SERVER.md). - -### O hazlo tú mismo - -[Descarga Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) y descomprímelo (o usa `git clone`). -**Windows:** haz doble clic en **`START-HERE.bat`**. **Linux:** ejecuta **`./setup.sh`** en la carpeta de Strata. - -**Mac (Apple Silicon, M1 a M5, macOS 15 o posterior):** instala una vez las Command Line Tools de Apple (`xcode-select --install` en Terminal; no hace falta Xcode). Luego abre Terminal en la carpeta de Strata y ejecuta **`./setup.sh`**. Compila el motor de Mac en tu Mac (unos 7 minutos), hace las mismas preguntas, descarga el modelo y lo arranca. La próxima vez, `./setup.sh` arranca enseguida. Qué tamaño cabe en tu Mac y qué velocidad tiene: [docs/MAC.md](docs/MAC.md). - -Los pasos son los mismos para NVIDIA y AMD. El instalador detecta tu tarjeta y prepara el motor adecuado para ella. -Te hace unas pocas preguntas: - -- qué modelo y qué tamaño, -- cuánto contexto (cuánto texto tiene presente el modelo), -- si debe entender imágenes. - -Pulsa Enter cada vez para usar la respuesta recomendada. Después descarga el modelo (unos 70 GB) y lo arranca. Si la -descarga se detiene, vuelve a ejecutarlo: sigue donde lo dejó. Tu navegador abre la aplicación de Strata en -`http://127.0.0.1:8080`. - -> **Mientras el modelo arranca, tu PC puede ir lento o dejar de responder durante 1-3 minutos** (más la primera vez). -> Strata carga 35-55 GB en tu RAM y reserva una parte para la tarjeta gráfica. Es normal. Espera y no cierres la -> ventana. La ventana muestra lo que está haciendo Strata. - -**La próxima vez**, vuelve a ejecutar `START-HERE.bat` (o `./setup.sh`). Arranca enseguida y no descarga nada dos -veces. Cierra su ventana para detener el modelo. `UPDATE.bat` (`./update.sh`) actualiza Strata sin arrancarlo. -Actualizaciones, Docker, varias tarjetas, dónde se guardan los archivos y todas las opciones: [docs/INSTALL.md](docs/INSTALL.md). - -## ¿Qué modelo elijo? - -El instalador te recomienda uno según tu RAM. El mismo modelo viene en varios tamaños, más o menos comprimidos. Los -tamaños pequeños son más rápidos. Los grandes son algo más inteligentes. - -| Tu RAM | Elige | Por qué | -| --- | --- | --- | -| **32 GB** | **Coder** | cabe en 32 GB y está hecho para programar (con una tarjeta de 24 GB también funcionan Q2_0 e IQ2_XS) | -| **48 GB** | **IQ2_XS** (o Q2_0, el más rápido) | los tamaños más grandes no caben | -| **64 GB** | **IQ2_XS** (recomendado), o IQ3_XXS / IQ3_S | caben todos los tamaños; IQ3_S es el mejor y el más lento | -| **96 GB o más** | **IQ3_S**, o el UD-IQ4_XS de Unsloth (~4 bits) | espacio para los tamaños más grandes con todo lo demás abierto | - -- **[Coder](docs/MODELS.md#coder):** una versión para programar a la que se le quitó la mitad de los expertos. Alcanza - el 91% de la puntuación SWE-bench Verified del modelo completo (medido por sus autores) y cabe en 32 GB de RAM. Es - más flojo fuera del código, también con chino y otros textos CJK (#438). Para eso, elige Q2_0, IQ2_XS o IQ3_S, que - conservan todos los expertos. -- **[Swift 1.5](docs/MODELS.md#swift-15):** un ajuste fino que piensa mucho menos tiempo antes de responder. Recibes - la respuesta antes, con más o menos la misma calidad. -- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** la versión de ~4 bits de Unsloth, entre IQ3_S y - UD-Q4_K_XL en calidad. Una descarga de 94 GB. Con menos de ~80 GB de RAM, Strata lee una parte desde el SSD - mientras responde, así que ahí es más lento (un SSD NVMe ayuda). -- **[Unsloth UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL y Q8_0](docs/MODELS.md#unsloths-files-ud-iq4_xs-to-q8_0):** de 4 a 8 bits, más cerca del modelo completo - (93-95 % el mismo token siguiente que Q8_0). Rápidos cuando todos los expertos caben en la RAM (~88 GB para - UD-Q4_K_XL hasta ~136 GB para Q8_0); con menos RAM, Strata lee una parte desde el SSD mientras responde, lo que es - mucho más lento (7-8.5 tokens/s para UD-Q4_K_XL en un PC con 64 GB). -- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** se instala a mano. No está en - el menú del instalador. - -Tamaños, descargas y qué cabe dónde: [docs/MODELS.md](docs/MODELS.md). Para añadir otro modelo más adelante, ejecuta -`SETUP.bat` (Linux: `./setup.sh --setup`). - -## Cómo usarlo - -

La pestaña Monitor de la aplicación de Strata junto a un agente de programación
-El Monitor de la aplicación de Strata (izquierda) mientras un agente de programación escribe el jardín de la pagoda del vídeo (derecha)

- -- **En el navegador:** abre `http://127.0.0.1:8080`. Tiene **Chat**, un **Monitor** en vivo del modelo y de tu - GPU/CPU/RAM, y **About** con los ajustes y las direcciones. -- **Tus aplicaciones y agentes de programación:** añade un proveedor "compatible con OpenAI" con la URL base - **`http://127.0.0.1:8080/v1`**. Sirve cualquier clave de API y cualquier nombre de modelo. - - Aplicaciones que usan la API de Anthropic: `http://127.0.0.1:8080/v1/messages` (Claude Code: - `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). - - Codex CLI y otras aplicaciones que usan la API Responses de OpenAI: `/v1/responses` - ([configuración](docs/DETAILS.md#the-responses-api-and-codex-cli)). -- **Razonamiento:** elige **off, low, medium o high** en el menú del chat o en el "reasoning effort" de tu aplicación. - Off es lo más rápido. High es lo mejor para preguntas difíciles. -- **Imágenes:** responde que sí a "Images?" en la instalación. Luego haz clic en **Picture** en el chat, o adjunta - imágenes en tu aplicación. Las tarjetas AMD leen imágenes en Linux a través del procesador; en Windows todavía no. -- **Desde tu móvil u otro PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `. Pon siempre una clave. -- **Una petición cada vez:** por defecto Strata responde una petición y las demás esperan. Para responder varias a la - vez, pon `"parallel": 2` ([BATCHING.md](docs/BATCHING.md)). En una tarjeta de 12 GB, cada respuesta va más lenta. -- **Prompts largos:** Strata lee entero el primer mensaje de un chat, más o menos 1 minuto por cada 30,000 tokens. Los - mensajes siguientes empiezan en segundos. - -Más: [dónde se guardan tus chats](docs/INSTALL.md#where-things-are-stored), [la API](docs/DETAILS.md#using-it). - -### Opcional: más velocidad con una sola tarjeta cuando todo el modelo cabe en la RAM - -Dos ajustes opcionales (de RubenTorney, #1904 y #1905). Ayudan si usas una tarjeta gráfica y tu RAM guarda todos los expertos (el modo arena de Strata, por ejemplo Q2_0 o IQ3_XXS en un PC con 64 GB). Abre tu configuración `strata-.json` en la carpeta de datos de Strata ([dónde](docs/INSTALL.md#where-things-are-stored)) y añade: - -- **Generación más rápida:** `"--adapt-async", "1"` en la lista `"args"`. La caché de expertos se actualiza entonces en un hilo auxiliar en vez de pausar la respuesta. Medido en una RTX 5070 (Windows, Q2_0): +4-5 % de generación, +7-10 % en código y documentos largos. Las respuestas pueden diferir un poco de las por defecto (son iguales de una ejecución a otra). -- **Lectura del prompt más rápida en Windows:** `"STRATA_PIN_BY_NEED": "1"` en el bloque `"env"`. Windows solo puede bloquear cerca de la mitad de la RAM para la tarjeta; esto bloquea primero los expertos que la tarjeta necesita de verdad. Medido en la RTX 5070: +4,4 % en la lectura del prompt. - -```json -"args": [ ..., "--adapt-async", "1" ], -"env": { "STRATA_PIN_BY_NEED": "1" } +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +En Windows, abre una terminal nueva después. Luego: + +```sh +strata launch ``` -Reinicia Strata (`START-HERE.bat` o `./setup.sh`) después del cambio. Para deshacerlo, quita las dos entradas. +Sigue las indicaciones para descargar e iniciar un modelo. [Guía del Terminal](docs/TERMINAL_LAUNCH.md). -## ¿Algo salió mal? +
+ +

+ Aplicación de Terminal de Strata con la actividad del modelo, la velocidad, la memoria y las peticiones recientes +
Observa tu modelo y tu hardware mientras se ejecuta. +

+ + + +[Compilar desde el código fuente](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guía de instalación completa](docs/INSTALL.md) + + + +## Hardware + +| Hardware compatible | Guía | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Instalación en NVIDIA](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Instalación en AMD](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · experimental** | [Instalación en RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Instalación en Intel](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 o posterior** | [Instalación en Mac](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Instalación en Strix Halo](docs/STRIX_HALO.md) | -- **Mi PC se congeló la primera vez que arrancó Strata.** Es normal mientras carga el modelo. Espera y no cierres la - ventana. ¿Sigue congelado después de 10 minutos? Reinicia el PC, cierra otros programas y vuelve a intentarlo, o - elige un tamaño más pequeño. -- **Se detuvo durante la descarga o la instalación.** Vuelve a ejecutar `START-HERE.bat` (o `./setup.sh`). Sigue - donde se detuvo. -- **Va muy lento y la luz del disco no deja de parpadear, o dice "the engine stopped unexpectedly".** Tu PC no tiene - suficiente RAM libre. Cierra otros programas (los navegadores usan mucha), o elige un tamaño más pequeño (Q2_0 o - IQ2_XS). -- **Dice que el puerto 8080 ya está en uso.** Strata ya está en marcha. Busca su ventana. + -Más problemas y sus soluciones: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). ¿Sigues atascado? Abre un -[issue](https://github.com/Niko1221/Strata/issues) y adjunta `strata-.log` de la carpeta de Strata. ¿Has -encontrado un problema de seguridad? Infórmalo en privado: [SECURITY.md](SECURITY.md). +## Herramientas -## ¿Cómo funciona? +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, y más, mediante las API compatibles con OpenAI y Anthropic. -Los modelos como este suelen funcionar en servidores con cientos de gigabytes de memoria gráfica. Tu tarjeta gráfica -tiene 12-24 GB. Strata hace que el modelo quepa **repartiendo el trabajo por todo tu PC**. Piensa en una cocina: lo -que usas todo el rato se queda en la encimera, y el resto espera en la despensa. +Ejecuta **`strata connect`** para ver las instrucciones de tu herramienta. [Guía de conexión](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). -

Los 24,576 expertos del modelo: los más usados en la tarjeta gráfica, todos en la RAM y una tabla de consulta en el SSD

+ + + + -- **El modelo es un equipo de 24,576 pequeños especialistas ("expertos").** Cada palabra solo necesita 10 de ellos. -- **Tu tarjeta gráfica** guarda los pocos miles de expertos que más se usan. **Tu RAM** los tiene todos, y **tu - procesador** trabaja con el resto al mismo tiempo. **Tu SSD** guarda una gran tabla de consulta. +## Ayuda -

Un pequeño ayudante adivina las siguientes palabras; el modelo grande las comprueba todas a la vez y se queda con las correctas

+[Todas las guías](docs) · [Solución de problemas](docs/TROUBLESHOOTING.md) · [Informar de un error](https://github.com/Niko1221/Strata/issues/new/choose) · +[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Cómo funciona](docs/HOW_IT_WORKS.md) · [Contribuir](CONTRIBUTING.md) -- **Adivinar y comprobar:** un pequeño ayudante adivina las siguientes palabras. El modelo grande las comprueba todas - a la vez. Recibes la misma respuesta, 1.6-1.8x antes. -- **Los textos largos se leen en trozos grandes** (hasta 8,192 tokens cada vez), a más de 1,000 tokens por segundo. +## Apoya Strata -La explicación larga: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Cada parte y sus números: -[los detalles](docs/DETAILS.md#how-it-works) y el [artículo](docs/paper/Strata-Paper.pdf). +**Ayuda a mantener la IA local abierta a todos.** Un café ayuda a financiar el desarrollo y las pruebas en más hardware. -## Créditos y licencia +Buy Me a Coffee: apoya Strata -El modelo es [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next), del equipo de Qwen. Lo -comprimieron [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) -y Unsloth. Strata usa partes de [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). Todos los créditos: -[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata es de código abierto con la [licencia MIT](LICENSE). -Algunas partes y cada modelo tienen sus propias licencias ([cuáles](docs/HOW_IT_WORKS.md#license)). +[Licencia MIT](LICENSE) · [Créditos y licencias de los modelos](docs/HOW_IT_WORKS.md#credits) · [Privacidad](docs/SAFETY.md) -## Apoya a Strata + -Strata es libre y de código abierto. Si te resulta útil, puedes apoyar su desarrollo: +Para herramientas de IA y lectores automáticos: referencia técnica · instrucciones de instalación. -

Buy Me A Coffee

+**Patrocinios, alianzas de hardware o colaboraciones:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/README.fr.md b/README.fr.md index 42462a28b44..1742238c35c 100644 --- a/README.fr.md +++ b/README.fr.md @@ -1,238 +1,188 @@ -

Strata

+

+ + + Strata + +

-[English](README.md) · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · [Deutsch](README.de.md) · **Français** · [Español](README.es.md) · [Português](README.pt-BR.md) +

Une IA puissante sur votre propre ordinateur.

+

Discutez, programmez et travaillez avec des images, en local.

-

Faites tourner un modèle d'IA de 125 milliards de paramètres sur votre propre PC de jeu
-Carte graphique NVIDIA ou AMD (12 Go ou plus) · Windows ou Linux · gratuit et open source

+

+ Modèles · Installation · + Matériel · Outils · + Aide · Soutenir +

-

Un jardin de pagode en voxels écrit par le modèle de Strata, qui tourne dans le navigateur
-Un jardin de pagode en voxels, généré en une seule requête sur une RTX 5070 avec Strata (IQ3_S, contexte de 128K) · -vidéo complète (49 s)

+

+ Télécharger Strata + Licence MIT + Soutenir Strata sur Buy Me a Coffee +

-Strata fait tourner **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** sur un PC normal. C'est -un grand modèle d'IA, très capable, qui demande d'habitude un serveur. Il discute, écrit du code, lit des images et -fonctionne avec vos applications et vos agents de code. Rien ne quitte votre PC. +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

-## Quelle est sa vitesse ? +**Gratuit, open source, et à vous de l'exécuter.** Utilisez Strata sur votre bureau ou avec vos outils de programmation préférés. Aucun compte nécessaire. -Nous l'avons mesurée sur deux PC de jeu ordinaires. Un token correspond à environ ¾ d'un mot. +## Modèles -- **Écrit les réponses :** la vitesse à laquelle la réponse s'affiche dans une courte discussion. 60 tokens par seconde, c'est plus rapide que votre lecture. -- **Lit votre prompt :** la vitesse à laquelle il absorbe ce que vous envoyez (ici un document, du code ou un historique de discussion de 32K tokens). +Nous recommandons **d'abord ISTA-DASLab**, puis **Unsloth** et d'autres fournisseurs, lorsqu'un modèle compatible tient en mémoire. - - - -
NVIDIA : RTX 5070 (12 Go), Ryzen 5 7600, 64 Go de RAMAMD : RX 9070 XT (16 Go), Ryzen 9 3900X, 47 Go de RAM
+
+  Qwen3.8-Flash-Next -| Taille | Écrit les réponses | Lit votre prompt | +| Fournisseur | Choix | +| --- | --- | +| **ISTA-DASLab · recommandé** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder : IQ1\_M](docs/MODELS.md#coder) pour programmer. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Utilise moins de mémoire, mais plus lent. | +| **Autres options** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Comparer les tailles, la mémoire nécessaire et la compatibilité](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Ce sont les paquets actuellement documentés pour ce modèle. + +[Guide du modèle et compatibilité](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +Dans l'**application de bureau** et dans le **Terminal**. Ce qui ne tient pas en mémoire est lu depuis votre SSD : il faut donc beaucoup d'espace disque libre. + +| Jeu (ISTA-DAS) | Téléchargement | Espace disque libre nécessaire | | --- | ---: | ---: | -| **Q2_0** | 94 tokens/s | 2,650 tokens/s | -| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | -| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | -| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | -| **Coder** | 55 tokens/s | 2,180 tokens/s | +| 1.75 bpw | 239 GB | environ 245 GB | +| 2.00 bpw | 257 GB | environ 265 GB | +| 2.25 bpw | 274 GB | environ 280 GB | + +Fonctionne sur les NVIDIA RTX 30, 40 et 50 (Windows et Linux) et sur l'AMD Radeon AI PRO R9700 (Linux). L'installation télécharge les fichiers et le moteur DeepSeek, puis démarre le modèle. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` -
+Mesuré avec le jeu 2.00 bpw sur Strata 0.2.5. « Sortie » est la vitesse de la réponse, « Prompt » la vitesse à laquelle Strata lit votre texte. -| Taille | Écrit les réponses | Lit votre prompt | +| Matériel | Sortie | Prompt | | --- | ---: | ---: | -| **Q2_0** | 60 tokens/s | 1,160 tokens/s | -| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | -| **Coder** | 44 tokens/s | 1,420 tokens/s | +| RTX 5070 12 GB, 64 GB de RAM | 4 à 6 tokens/s | environ 110 tokens/s (4K) | +| RTX 3060 12 GB, 46 GB de RAM | 9 à 11 tokens/s | environ 155 tokens/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 à 25 tokens/s | 320 à 360 tokens/s (8K) | +| 4x Radeon AI PRO R9700 | 74 à 77 tokens/s | 400 à 450 tokens/s (8K) | -
+[Mémoire, disque et détails](docs/DEEPSEEK41.md) · [Notes de version](https://github.com/Niko1221/Strata/releases) -NVIDIA : Q2_0 avec le moteur 0.1.36, les autres lignes avec 0.1.26 (réponses de 4K, prompts de 32K). Les tableaux -complets sont dans [DETAILS.md](docs/DETAILS.md#speed-measured). Une carte avec plus de VRAM va plus vite : une -RTX 3090 (24 Go) devrait écrire environ 100-140 tokens par seconde. Longues discussions et autres cartes : -[vitesse de chaque modèle](docs/MODELS.md#how-fast-is-each-size), [résultats de la communauté](docs/COMMUNITY_BENCHMARKS.md). + -

Buy Me A Coffee
-Strata est gratuit. S'il tourne bien sur votre PC, un café aide à poursuivre le travail.

+ -## Ce qu'il vous faut +Vous ne savez pas ce qui tient ? [Choisir un modèle pour votre ordinateur](docs/MODELS.md#pick-by-memory). -| | | -| --- | --- | -| **Carte graphique** | **NVIDIA** GeForce RTX série 20, 30, 40 ou 50, ou **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 ou série RX 6800 / 6900. Il faut **12 Go de VRAM ou plus**. | -| **RAM** | 32 Go ou plus. Votre RAM décide [quel modèle](#quel-modèle-choisir-) tient. Avec 64 Go, toutes les tailles tournent. | -| **Disque** | Environ 80 Go libres. Prenez un SSD si possible : le premier démarrage est bien plus rapide. | -| **Système** | Windows 10 / 11 ou Linux, avec un pilote graphique NVIDIA ou AMD à jour. | +## Installation -L'installateur s'occupe de tout le reste. Deux ou trois cartes peuvent se partager le modèle ([multi-GPU](docs/MULTI_GPU.md)). + -Expérimental, écrit et testé par des membres de la communauté sur leurs propres machines : +### Application de bureau -- **Cartes graphiques plus anciennes** (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT) : [Older GPUs](docs/OLDER_GPUS.md). -- **Intel Arc**, compilé depuis les sources sous Linux : [Intel Arc](docs/INTEL_ARC.md). -- **AMD Ryzen AI Max (Strix Halo)**, compilé depuis les sources sous Linux : [Strix Halo](docs/STRIX_HALO.md). -- **Processeurs plus anciens sans AVX2** : ça marche, mais lentement. [Older CPUs](docs/INSTALL.md#older-cpus-experimental). +**[Télécharger Strata pour Windows, Linux ou Mac →](https://github.com/Niko1221/Strata/releases/latest)** -La liste complète : [docs/INSTALL.md](docs/INSTALL.md#what-you-need). +Installez l'application, choisissez un modèle et commencez à discuter. Il y a un seul installateur par système. Au premier lancement, l'application télécharge le moteur de votre carte graphique. [Aide pour l'installateur](docs/INSTALL.md#the-app). -## Installation +Fichiers: `Strata-0.2.9-windows-x64-setup.exe` · `Strata-0.2.9-linux-x86_64.AppImage` · `Strata-0.2.9-macos-arm64.dmg` -### Laissez votre IA l'installer +

+ Application de bureau Strata avec une discussion et un aperçu du code en direct côte à côte +
Discussion, fichiers et aperçu en direct dans une seule fenêtre. +

-Vous utilisez un assistant de code IA (Claude Code, Cursor, Codex, GitHub Copilot, ...) ? Collez-lui ceci : + -```text -Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +### Application Terminal + +Vous préférez le terminal ? Installez Strata, puis lancez **`strata launch`**. + +
+Commandes d'installation + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh ``` -Il vérifie votre carte graphique, votre RAM et votre disque, et choisit le modèle qui convient. Ensuite il l'installe, -le démarre et vous explique comment connecter vos applications. Les outils d'IA peuvent aussi installer, démarrer et -arrêter Strata grâce à son [serveur MCP](docs/MCP_SERVER.md). - -### Ou faites-le vous-même - -[Téléchargez Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) et décompressez-le (ou faites un `git clone`). -**Windows :** double-cliquez sur **`START-HERE.bat`**. **Linux :** lancez **`./setup.sh`** dans le dossier Strata. - -**Mac (Apple Silicon, M1 à M5, macOS 15 ou plus récent) :** installez une fois les Command Line Tools d'Apple (`xcode-select --install` dans le Terminal ; Xcode lui-même n'est pas nécessaire). Ouvrez ensuite le Terminal dans le dossier Strata et lancez **`./setup.sh`**. Il compile le moteur Mac sur votre Mac (environ 7 minutes), pose les mêmes questions, télécharge le modèle et le démarre. La fois suivante, `./setup.sh` démarre tout de suite. Quelle taille convient à votre Mac et sa vitesse : [docs/MAC.md](docs/MAC.md). - -Les étapes sont les mêmes pour NVIDIA et AMD. L'installateur détecte votre carte et installe le bon moteur pour elle. -Il vous pose quelques questions : - -- quel modèle et quelle taille, -- combien de contexte (la quantité de texte que le modèle garde en tête), -- s'il doit lire les images. - -Appuyez sur Entrée à chaque fois pour garder la réponse recommandée. Ensuite il télécharge le modèle (environ 70 Go) -et le démarre. Si le téléchargement s'arrête, relancez-le : il reprend là où il s'était arrêté. Votre navigateur -ouvre l'application Strata à l'adresse `http://127.0.0.1:8080`. - -> **Pendant le démarrage du modèle, votre PC peut ralentir ou ne plus répondre pendant 1-3 minutes** (plus longtemps la première fois). -> Strata charge 35-55 Go dans votre RAM et en réserve une partie pour la carte graphique. C'est normal. Attendez, et -> ne fermez pas la fenêtre. La fenêtre montre ce que fait Strata. - -**La fois suivante**, relancez `START-HERE.bat` (ou `./setup.sh`). Il démarre tout de suite et ne télécharge rien -deux fois. Fermez sa fenêtre pour arrêter le modèle. `UPDATE.bat` (`./update.sh`) met Strata à jour sans le démarrer. -Mises à jour, Docker, plusieurs cartes, emplacement des fichiers et toutes les options : [docs/INSTALL.md](docs/INSTALL.md). - -## Quel modèle choisir ? - -L'installateur en recommande un selon votre RAM. Le même modèle existe en plusieurs tailles, plus ou moins -compressées. Les petites tailles sont plus rapides. Les grandes sont un peu plus intelligentes. - -| Votre RAM | Prenez | Pourquoi | -| --- | --- | --- | -| **32 Go** | **Coder** | il tient dans 32 Go et il est fait pour le code (avec une carte de 24 Go, Q2_0 et IQ2_XS tournent aussi) | -| **48 Go** | **IQ2_XS** (ou Q2_0, le plus rapide) | les plus grandes tailles ne tiennent pas | -| **64 Go** | **IQ2_XS** (recommandé), ou IQ3_XXS / IQ3_S | toutes les tailles tiennent ; IQ3_S est le meilleur et le plus lent | -| **96 Go ou plus** | **IQ3_S**, ou l'UD-IQ4_XS d'Unsloth (~4 bits) | de la place pour les plus grandes tailles, avec tout le reste ouvert | - -- **[Coder](docs/MODELS.md#coder) :** une version pour le code, avec la moitié des experts en moins. Elle atteint 91 % - du score SWE-bench Verified du modèle complet (mesuré par ses auteurs) et tient dans 32 Go de RAM. Elle est moins - bonne en dehors du code, y compris pour le chinois et les autres textes CJK (#438). Pour ces cas, prenez Q2_0, - IQ2_XS ou IQ3_S, qui gardent tous les experts. -- **[Swift 1.5](docs/MODELS.md#swift-15) :** un fine-tune qui réfléchit bien moins longtemps avant de répondre. Vous - avez la réponse plus tôt, avec à peu près la même qualité. -- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs)** : la version ~4 bits d'Unsloth, entre IQ3_S et - UD-Q4_K_XL en qualité. Un téléchargement de 94 Go. Avec moins de ~80 Go de RAM, Strata en lit une partie depuis - le SSD pendant qu'il répond, il y est donc plus lent (un SSD NVMe aide). -- **[Unsloth UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL et Q8_0](docs/MODELS.md#unsloths-files-ud-iq4_xs-to-q8_0) :** de 4 à 8 bits, plus proches du modèle - complet (93-95 % le même token suivant que Q8_0). Rapides quand tous les experts tiennent dans la RAM (~88 Go pour - UD-Q4_K_XL jusqu'à ~136 Go pour Q8_0) ; avec moins de RAM, Strata en lit une partie depuis le SSD pendant qu'il - répond, ce qui est bien plus lent (7-8.5 tokens/s pour UD-Q4_K_XL sur un PC avec 64 Go). -- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs) :** vous l'installez à la main. - Il n'est pas dans le menu de l'installateur. - -Tailles, téléchargements et ce qui tient où : [docs/MODELS.md](docs/MODELS.md). Pour ajouter un autre modèle plus -tard, lancez `SETUP.bat` (Linux : `./setup.sh --setup`). - -## Utilisation - -

L'onglet Monitor de l'application Strata à côté d'un agent de code
-Le Monitor de l'application Strata (à gauche) pendant qu'un agent de code écrit le jardin de pagode de la vidéo (à droite)

- -- **Dans le navigateur :** ouvrez `http://127.0.0.1:8080`. Vous y trouvez **Chat**, un **Monitor** en direct du - modèle et de votre GPU/CPU/RAM, et **About** avec les réglages et les adresses. -- **Vos applications et agents de code :** ajoutez un fournisseur « OpenAI-compatible » avec l'URL de base - **`http://127.0.0.1:8080/v1`**. N'importe quelle clé API et n'importe quel nom de modèle fonctionnent. - - Applications qui utilisent l'API d'Anthropic : `http://127.0.0.1:8080/v1/messages` (Claude Code : - `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). - - Codex CLI et les autres applications qui utilisent l'API OpenAI Responses : `/v1/responses` - ([configuration](docs/DETAILS.md#the-responses-api-and-codex-cli)). -- **Réflexion :** choisissez **off, low, medium ou high** dans le menu du chat ou dans le « reasoning effort » de - votre application. Off est le plus rapide. High est le meilleur pour les questions difficiles. -- **Images :** répondez oui à « Images? » pendant l'installation. Ensuite cliquez sur **Picture** dans le chat, ou - joignez des images dans votre application. Les cartes AMD lisent les images sous Linux via le processeur ; sous - Windows, pas encore. -- **Depuis votre téléphone ou un autre PC :** `START-HERE.bat --setup --host 0.0.0.0 --api-key `. Définissez - toujours une clé. -- **Une requête à la fois :** par défaut, Strata répond à une requête et les autres attendent. Pour répondre à - plusieurs en même temps, mettez `"parallel": 2` ([BATCHING.md](docs/BATCHING.md)). Sur une carte de 12 Go, chaque - réponse devient alors plus lente. -- **Longs prompts :** Strata lit en entier le premier message d'une discussion, environ 1 minute pour 30,000 tokens. - Les messages suivants démarrent en quelques secondes. - -Plus d'infos : [où sont stockées vos discussions](docs/INSTALL.md#where-things-are-stored), [l'API](docs/DETAILS.md#using-it). - -### Optionnel : plus de vitesse sur une seule carte quand tout le modèle tient en RAM - -Deux réglages optionnels (de RubenTorney, #1904 et #1905). Ils aident si vous utilisez une seule carte graphique et que votre RAM contient tous les experts (le mode arena de Strata, par exemple Q2_0 ou IQ3_XXS sur un PC de 64 Go). Ouvrez votre configuration `strata-.json` dans le dossier de données de Strata ([où](docs/INSTALL.md#where-things-are-stored)) et ajoutez : - -- **Génération plus rapide :** `"--adapt-async", "1"` dans la liste `"args"`. Le cache d'experts est alors mis à jour dans un thread auxiliaire au lieu de mettre la réponse en pause. Mesuré sur une RTX 5070 (Windows, Q2_0) : +4-5 % de génération, +7-10 % sur le code et les longs documents. Les réponses peuvent légèrement différer de celles par défaut (elles restent identiques d'une exécution à l'autre). -- **Lecture du prompt plus rapide sous Windows :** `"STRATA_PIN_BY_NEED": "1"` dans le bloc `"env"`. Windows ne peut verrouiller qu'environ la moitié de la RAM pour la carte ; ce réglage verrouille d'abord les experts dont la carte a vraiment besoin. Mesuré sur la RTX 5070 : +4,4 % en lecture du prompt. - -```json -"args": [ ..., "--adapt-async", "1" ], -"env": { "STRATA_PIN_BY_NEED": "1" } +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex ``` -Redémarrez Strata (`START-HERE.bat` ou `./setup.sh`) après la modification. Pour annuler, retirez les deux entrées. +Sous Windows, ouvrez ensuite un nouveau terminal. Puis : + +```sh +strata launch +``` -## Un problème ? +Suivez les invites pour télécharger et démarrer un modèle. [Guide du Terminal](docs/TERMINAL_LAUNCH.md). -- **Mon PC s'est figé au premier démarrage de Strata.** C'est normal pendant le chargement du modèle. Attendez, et ne - fermez pas la fenêtre. Toujours figé après 10 minutes ? Redémarrez le PC, fermez les autres programmes et - réessayez, ou choisissez une taille plus petite. -- **Il s'est arrêté pendant le téléchargement ou l'installation.** Relancez `START-HERE.bat` (ou `./setup.sh`). Il - reprend là où il s'était arrêté. -- **C'est très lent et le voyant du disque clignote sans arrêt, ou il affiche « the engine stopped unexpectedly ».** - Votre PC n'a pas assez de RAM libre. Fermez les autres programmes (les navigateurs en utilisent beaucoup), ou - choisissez une taille plus petite (Q2_0 ou IQ2_XS). -- **Il dit que le port 8080 est déjà utilisé.** Strata tourne déjà. Cherchez sa fenêtre. +
-Autres problèmes et leurs solutions : [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Toujours bloqué ? Ouvrez une -[issue](https://github.com/Niko1221/Strata/issues) et joignez `strata-.log` depuis le dossier Strata. Vous -avez trouvé un problème de sécurité ? Signalez-le en privé : [SECURITY.md](SECURITY.md). +

+ Application Terminal de Strata affichant l'activité du modèle, la vitesse, la mémoire et les requêtes récentes +
Suivez votre modèle et votre matériel pendant qu'il tourne. +

-## Comment ça marche ? + -Les modèles comme celui-ci tournent d'habitude sur des serveurs avec des centaines de gigaoctets de mémoire -graphique. Votre carte graphique a 12-24 Go. Strata fait tenir le modèle en **répartissant le travail sur tout votre -PC**. Pensez à une cuisine : ce que vous utilisez tout le temps reste sur le plan de travail, et le reste attend dans -le placard. +[Compiler depuis les sources](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guide d'installation complet](docs/INSTALL.md) -

Les 24,576 experts du modèle : les plus sollicités sur la carte graphique, tous en RAM, une table de correspondance sur le SSD

+ -- **Le modèle est une équipe de 24,576 petits spécialistes (les « experts »).** Chaque mot n'en demande que 10. -- **Votre carte graphique** garde les quelques milliers d'experts les plus utilisés. **Votre RAM** les contient tous, - et **votre processeur** travaille sur les autres en même temps. **Votre SSD** contient une grande table de - correspondance. +## Matériel -

Un petit assistant devine les mots suivants ; le grand modèle les vérifie tous d'un coup et garde les bons

+| Matériel pris en charge | Guide | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Installation NVIDIA](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Installation AMD](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · expérimental** | [Installation RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Installation Intel](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 ou plus récent** | [Installation sur Mac](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Installation Strix Halo](docs/STRIX_HALO.md) | -- **Deviner, puis vérifier :** un petit assistant devine les quelques mots suivants. Le grand modèle les vérifie - tous d'un coup. Vous obtenez la même réponse, 1.6-1.8x plus tôt. -- **Les longs textes sont lus par gros morceaux** (jusqu'à 8,192 tokens à la fois), à plus de 1,000 tokens par seconde. + -L'explication plus longue : [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Chaque partie et ses chiffres : -[les détails](docs/DETAILS.md#how-it-works) et l'[article](docs/paper/Strata-Paper.pdf). +## Outils -## Crédits et licence +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, et d'autres via les API compatibles OpenAI et Anthropic. -Le modèle est [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next), de l'équipe Qwen. Il a été -compressé par [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) -et Unsloth. Strata utilise des parties de [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). Tous les -crédits : [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata est open source sous [licence MIT](LICENSE). -Quelques parties et chaque modèle ont leur propre licence ([lesquelles](docs/HOW_IT_WORKS.md#license)). +Lancez **`strata connect`** pour voir la configuration de votre outil. [Guide de connexion](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). + + + + + + +## Aide + +[Tous les guides](docs) · [Dépannage](docs/TROUBLESHOOTING.md) · [Signaler un bogue](https://github.com/Niko1221/Strata/issues/new/choose) · +[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Comment ça marche](docs/HOW_IT_WORKS.md) · [Contribuer](CONTRIBUTING.md) ## Soutenir Strata -Strata est gratuit et open source. S'il vous est utile, vous pouvez soutenir son développement : +**Aidez à garder l'IA locale ouverte à tous.** Un café aide à financer le développement et les tests sur davantage de matériel. + +Buy Me a Coffee : soutenir Strata + +[Licence MIT](LICENSE) · [Crédits et licences des modèles](docs/HOW_IT_WORKS.md#credits) · [Confidentialité](docs/SAFETY.md) + + + +Pour les outils d'IA et les lecteurs automatiques : référence technique · instructions d'installation. -

Buy Me A Coffee

+**Parrainages, partenariats matériel ou collaborations :** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/README.ja.md b/README.ja.md index 3fc7d2cbd12..0ec6d2e3f1d 100644 --- a/README.ja.md +++ b/README.ja.md @@ -1,229 +1,188 @@ -

Strata

+

+ + + Strata + +

-[English](README.md) · [简体中文](README.zh-CN.md) · **日本語** · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · [Português](README.pt-BR.md) +

あなた自身のパソコンで、高性能な AI を。

+

チャット、コーディング、画像の処理を、すべてローカルで。

-

1,250 億パラメータの AI モデルを、手元のゲーミング PC で動かす
-NVIDIA または AMD のグラフィックカード(12 GB 以上) · Windows または Linux · 無料・オープンソース

+

+ モデル · インストール · + ハードウェア · ツール · + ヘルプ · 支援 +

-

Strata で生成した、五重塔のある庭。ボクセルで表現され、ブラウザーで動作している
-五重塔のある庭をボクセルで表現。RTX 5070 で動かした Strata(IQ3_S、コンテキスト長 128K)に、1 回のプロンプトで作成を依頼 · -動画を見る(全編 49 秒)

+

+ Strata をダウンロード + MIT ライセンス + Buy Me a Coffee で Strata を支援する +

-Strata を使うと、**[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** を一般的な PC で動かせます。 -通常はサーバーを必要とする大規模で高性能な AI モデルで、チャットやコードの生成、画像の読み取りができます。 -アプリやコーディングエージェントとも連携でき、データは PC の外に送信されません。 +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

-## どのくらい速い? +**無料でオープンソース。自分の環境で動かせます。** デスクトップで、またはお好みのコーディングツールと一緒に Strata を使えます。アカウントは不要です。 -一般的なゲーミング PC 2 台で速度を測定しました。英語の場合、1 トークンはおよそ ¾ 語に相当します。 +## モデル -- **生成速度:** 短いチャットで回答を生成する速度です。毎秒 60 トークンなら、人が読むよりも速く文章が表示されます。 -- **プロンプトの読み込み:** 入力した内容を読み込む速度です。ここでは、文書やコード、チャット履歴など 32K トークン分を読み込ませています。 +まず **ISTA-DASLab** をおすすめします。次に **Unsloth** などの提供元です。メモリに収まる互換モデルがある場合に選べます。 - - - -
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM
+
+  Qwen3.8-Flash-Next -| モデルサイズ | 生成速度 | プロンプトの読み込み | +| 提供元 | 選択肢 | +| --- | --- | +| **ISTA-DASLab · おすすめ** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S。[Coder: IQ1\_M](docs/MODELS.md#coder)(コーディング向け)。 | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF)。メモリ使用量は少ないですが、動作は遅くなります。 | +| **その他の選択肢** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[サイズ、必要なメモリ、互換性を比べる](docs/MODELS.md)。 + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0。現在、このモデルで文書化されているパックです。 + +[モデルガイドと互換性](docs/QWEN36.md)。 + +
+ +
+  DeepSeekV4.1-Flash-1017 + +**デスクトップアプリ**と**ターミナル**で使えます。メモリに収まらない分は SSD から読み込むため、空きディスク容量がたくさん必要です。 + +| セット(ISTA-DAS) | ダウンロード | 必要な空き容量 | | --- | ---: | ---: | -| **Q2_0** | 94 tokens/s | 2,650 tokens/s | -| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | -| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | -| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | -| **Coder** | 55 tokens/s | 2,180 tokens/s | +| 1.75 bpw | 239 GB | 約245 GB | +| 2.00 bpw | 257 GB | 約265 GB | +| 2.25 bpw | 274 GB | 約280 GB | + +NVIDIA RTX 30・40・50 シリーズ(Windows と Linux)と、AMD Radeon AI PRO R9700(Linux)で動きます。セットアップがファイルと DeepSeek エンジンをダウンロードし、モデルを起動します。 + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` -
+Strata 0.2.5 で 2.00 bpw のセットを使って測定しました。「出力」は回答の速さ、「プロンプト」は Strata が入力を読み込む速さです。 -| モデルサイズ | 生成速度 | プロンプトの読み込み | +| ハードウェア | 出力 | プロンプト | | --- | ---: | ---: | -| **Q2_0** | 60 tokens/s | 1,160 tokens/s | -| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | -| **Coder** | 44 tokens/s | 1,420 tokens/s | +| RTX 5070 12 GB, 64 GB RAM | 4〜6 トークン/秒 | 約 110 トークン/秒 (4K) | +| RTX 3060 12 GB, 46 GB RAM | 9〜11 トークン/秒 | 約 155 トークン/秒 (4K) | +| 1x Radeon AI PRO R9700, 251 GB RAM | 21〜25 トークン/秒 | 320〜360 トークン/秒 (8K) | +| 4x Radeon AI PRO R9700 | 74〜77 トークン/秒 | 400〜450 トークン/秒 (8K) | -
+[メモリ、ディスク、詳細](docs/DEEPSEEK41.md) · [リリースノート](https://github.com/Niko1221/Strata/releases) -NVIDIA の測定には、Q2_0 のみエンジン 0.1.36、それ以外は 0.1.26 を使用しています(回答 4K、プロンプト 32K)。測定結果の詳細は -[DETAILS.md](docs/DETAILS.md#speed-measured) をご覧ください。VRAM の容量が大きいカードほど高速で、RTX 3090(24 GB)なら -毎秒およそ 100-140 トークンの生成速度が見込めます。長いチャットや他のカードでの性能については、[モデルごとの速度](docs/MODELS.md#how-fast-is-each-size)や -[コミュニティの測定結果](docs/COMMUNITY_BENCHMARKS.md)を参照してください。 + -

Buy Me A Coffee
-Strata は無料で使えます。お使いの PC で快適に動いたら、コーヒー 1 杯分のご支援が開発を続ける励みになります。

+ -## 必要なもの +どれが動くかわからない場合は、[お使いのパソコンに合うモデルを選ぶ](docs/MODELS.md#pick-by-memory)。 -| | | -| --- | --- | -| **グラフィックカード** | **NVIDIA** GeForce RTX 20、30、40、50 シリーズ、または **AMD** Radeon RX 7900 XT / XTX、RX 7800 XT / 7700 XT、RX 9060 XT、RX 9070 / 9070 XT、Radeon AI PRO R9700、RX 6800 / 6900 シリーズ。**VRAM 12 GB 以上**が必要です。 | -| **RAM** | 32 GB 以上。[利用できるモデル](#どのモデルを選べばいい)は RAM の容量によって異なります。64 GB あれば、どのサイズも利用できます。 | -| **ディスク** | 約 80 GB の空き容量。SSD を使うと初回の起動が大幅に速くなるため、おすすめです。 | -| **OS** | Windows 10 / 11 または Linux。NVIDIA または AMD の最新のグラフィックドライバーも必要です。 | +## インストール -その他の必要なソフトウェアは、インストーラーが用意します。2 枚または 3 枚のカードにモデルを分散させることもできます([マルチ GPU](docs/MULTI_GPU.md))。 + -以下のハードウェアにも試験的に対応しています。いずれもコミュニティのメンバーが手元のマシンで実装・テストしたものです。 +### デスクトップアプリ -- **旧世代のグラフィックカード**(Tesla P40 / V100、GTX 10、Radeon VII / MI50、RX 6700 XT、RX 5500 XT):[旧世代 GPU の対応状況](docs/OLDER_GPUS.md)。 -- **Intel Arc**(Linux でソースからビルド):[Intel Arc の対応状況](docs/INTEL_ARC.md)。 -- **AMD Ryzen AI Max(Strix Halo)**(Linux でソースからビルド):[Strix Halo の対応状況](docs/STRIX_HALO.md)。 -- **AVX2 非対応の旧世代 CPU**:動作しますが、速度は遅くなります。[旧世代 CPU の対応状況](docs/INSTALL.md#older-cpus-experimental)を参照してください。 +**[Windows、Linux、Mac 用の Strata をダウンロード →](https://github.com/Niko1221/Strata/releases/latest)** -必要な環境の一覧は、[docs/INSTALL.md](docs/INSTALL.md#what-you-need)をご覧ください。 +アプリをインストールし、モデルを選んで、チャットを始めましょう。インストーラーはシステムごとに1つです。初回起動時に、アプリがお使いのグラフィックスカード用のエンジンをダウンロードします。[インストーラーのヘルプ](docs/INSTALL.md#the-app)。 -## インストール +ファイル: `Strata-0.2.9-windows-x64-setup.exe` · `Strata-0.2.9-linux-x86_64.AppImage` · `Strata-0.2.9-macos-arm64.dmg` -### AI にセットアップしてもらう +

+ チャットとライブのコードプレビューを並べて表示した Strata デスクトップアプリ +
チャット、ファイル、ライブプレビューを1つのウィンドウで。 +

-Claude Code、Cursor、Codex、GitHub Copilot などの AI コーディングアシスタントを使っている場合は、次の文を貼り付けてください。 + -```text -Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +### ターミナルアプリ + +ターミナルのほうが好みですか? Strata をインストールして、**`strata launch`** を実行します。 + +
+インストールコマンド + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh ``` -AI がグラフィックカード、RAM、ディスクを確認して、PC に合ったモデルを選びます。インストールと起動を行い、 -アプリとの接続方法も案内します。また、Strata の [MCP サーバー](docs/MCP_SERVER.md) を使えば、 -AI ツールから Strata のインストール・起動・停止を行えます。 - -### 自分でやる - -[Strata をダウンロード](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip)して展開します(`git clone` でも構いません)。 -**Windows:** **`START-HERE.bat`** をダブルクリックします。**Linux:** Strata フォルダーで **`./setup.sh`** を実行します。 - -**Mac(Apple シリコン、M1〜M5、macOS 15 以降):** まず一度だけ Apple の Command Line Tools をインストールします(ターミナルで `xcode-select --install`。Xcode 本体は不要です)。次に Strata フォルダーでターミナルを開き、**`./setup.sh`** を実行します。Mac 用エンジンをお使いの Mac 上でビルドし(約 7 分)、同じ質問をしてからモデルをダウンロードして起動します。次回からは `./setup.sh` ですぐに起動します。どのサイズが Mac に合うかと速度:[docs/MAC.md](docs/MAC.md)。 - -NVIDIA でも AMD でも手順は同じです。インストーラーがカードを検出し、対応するエンジンを用意します。 -続いて、次の項目を設定します。 - -- 使用するモデルとサイズ -- コンテキストの長さ(モデルが覚えておけるテキストの量) -- 画像を読み取る機能を使うかどうか - -各項目で Enter を押すと、推奨設定が選ばれます。設定が終わるとモデル(約 70 GB)をダウンロードし、起動します。 -ダウンロードが途中で止まった場合は、もう一度実行すると続きから再開できます。起動が完了すると、ブラウザーで -`http://127.0.0.1:8080` が開き、Strata の画面が表示されます。 - -> **モデルの起動中は、1-3 分ほど PC の動作が遅くなったり、応答しなくなったりすることがあります**(初回は特に時間がかかります)。 -> Strata が 35-55 GB のデータを RAM に読み込み、その一部をグラフィックカード用に固定(ピン留め)しているためです。 -> 正常な動作なので、ウィンドウに表示される処理状況を確認しながら、閉じずにお待ちください。 - -**次回からは** `START-HERE.bat`(または `./setup.sh`)を実行するだけですぐに起動できます。2 回目以降は、ダウンロード済みのファイルを再度取得する必要はありません。 -モデルを停止するにはウィンドウを閉じてください。`UPDATE.bat`(`./update.sh`)を使うと、Strata を起動せずに更新できます。 -更新方法や Docker、複数のカードの使い方、ファイルの保存先、各種オプションについては、[docs/INSTALL.md](docs/INSTALL.md)をご覧ください。 - -## どのモデルを選べばいい - -インストーラーが RAM の容量に合ったモデルをおすすめします。同じモデルでも、圧縮率によって複数のサイズが用意されています。 -サイズが小さいほど高速に動作し、大きいほど回答の品質が少し高くなります。 - -| RAM | おすすめのモデル | 選ぶ理由 | -| --- | --- | --- | -| **32 GB** | **Coder** | 32 GB で動作するコーディング向けモデル(24 GB のカードがあれば Q2_0 と IQ2_XS も動作) | -| **48 GB** | **IQ2_XS**(速度優先なら Q2_0) | これより大きいサイズはメモリに収まらない | -| **64 GB** | **IQ2_XS**(おすすめ)、または IQ3_XXS / IQ3_S | どのサイズも利用可能。IQ3_S は回答の品質が最も高い一方、速度は最も遅い | -| **96 GB 以上** | **IQ3_S**、または Unsloth の UD-IQ4_XS(約 4-bit) | 他のアプリを開いたままでも、最大サイズのモデルを動かせるだけの余裕がある | - -- **[Coder](docs/MODELS.md#coder):** エキスパートを半分に減らしたコーディング向けモデルです。SWE-bench Verified ではフルモデルのスコアの - 91% を達成しており(開発者による測定)、32 GB の RAM で動作します。ただし、コード以外の用途では性能が劣り、中国語などの CJK 言語の処理も苦手です(#438)。 - こうした用途には、すべてのエキスパートを残した Q2_0、IQ2_XS、IQ3_S を選んでください。 -- **[Swift 1.5](docs/MODELS.md#swift-15):** 回答前の思考時間が大幅に短くなるようファインチューニングしたモデルです。 - 回答の品質をほぼ保ったまま、より短い時間で答えが返ってきます。 -- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** Unsloth による約 4-bit のモデルです。回答の品質は IQ3_S と UD-Q4_K_XL の中間です。 - ダウンロード容量は 94 GB です。RAM が約 80 GB 未満の場合、回答の生成中にモデルの一部を SSD から読み込むため、速度が落ちます(NVMe SSD を使うと改善します)。 -- **[Unsloth UD-Q4_K_XL / UD-Q5_K_XL / UD-Q6_K_XL / Q8_0](docs/MODELS.md#unsloths-files-ud-iq4_xs-to-q8_0):** 4〜8 ビットで、フルモデルにより近いモデルです - (次のトークンが Q8_0 と一致する割合は 93〜95%)。すべてのエキスパートが RAM に収まる場合(UD-Q4_K_XL で約 88 GB、 - Q8_0 で約 136 GB)は高速です。RAM が足りない場合は回答の生成中に一部を SSD から読み込むため、大幅に遅くなります - (RAM が 64 GB の PC で UD-Q4_K_XL は毎秒 7-8.5 トークン程度)。 -- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** 手動でのセットアップが必要です。 - インストーラーのメニューからは選べません。 - -各サイズのダウンロード情報や必要なメモリ容量は、[docs/MODELS.md](docs/MODELS.md)をご覧ください。後から別のモデルを追加する場合は、 -`SETUP.bat`(Linux:`./setup.sh --setup`)を実行してください。 - -## 使い方 - -

Strata の Monitor タブ(左)と、コードを生成するコーディングエージェント(右)
-動画に登場する五重塔の庭を作成中の画面。左が Strata の Monitor、右がコードを生成しているコーディングエージェント

- -- **ブラウザーで使う:** `http://127.0.0.1:8080` を開きます。チャット用の **Chat**、モデルや GPU/CPU/RAM の状態をリアルタイムで確認できる **Monitor**、 - 設定や接続先のアドレスを確認できる **About** の各タブがあります。 -- **アプリやコーディングエージェントと連携する:** 「OpenAI-compatible」プロバイダーを追加し、ベース URL に - **`http://127.0.0.1:8080/v1`** を指定します。API キーとモデル名には任意の値を指定できます。 - - Anthropic API を使うアプリ:`http://127.0.0.1:8080/v1/messages`(Claude Code では - `ANTHROPIC_BASE_URL=http://127.0.0.1:8080` を設定)。 - - Codex CLI など、OpenAI Responses API を使うアプリ:`/v1/responses` - ([設定方法](docs/DETAILS.md#the-responses-api-and-codex-cli))。 -- **思考(Thinking)の設定:** チャットのメニュー、または連携先アプリの「reasoning effort」で **off、low、medium、high** から選びます。 - off が最も速く、難しい質問には high が向いています。 -- **画像を読み取る:** セットアップ時に「Images?」で yes を選びます。その後、チャットの **Picture** ボタンをクリックするか、連携先のアプリで画像を添付してください。 - AMD のカードを使う場合、Linux では CPU で画像を読み取ります。Windows ではまだ画像の読み取りに対応していません。 -- **スマートフォンや別の PC から使う:** `START-HERE.bat --setup --host 0.0.0.0 --api-key ` で起動します。API キーは必ず設定してください。 -- **リクエストは 1 つずつ:** 標準設定では 1 つずつ処理し、それ以外のリクエストは順番を待ちます。同時に処理するには、 - `"parallel": 2` を設定してください([BATCHING.md](docs/BATCHING.md))。12 GB のカードでは、リクエストごとの回答速度が落ちます。 -- **長いプロンプトを送る:** チャットの最初のメッセージは全文を読み込むため、30,000 トークンあたり約 1 分かかります。 - 2 通目以降は数秒で応答が始まります。 - -[チャットの保存場所](docs/INSTALL.md#where-things-are-stored)や[API の詳細](docs/DETAILS.md#using-it)も参照してください。 - -### オプション:モデル全体が RAM に収まる場合、GPU 1 枚でさらに高速化 - -2 つのオプトイン設定です(RubenTorney 氏による #1904 と #1905)。GPU を 1 枚使い、RAM にすべてのエキスパートが収まる場合(Strata の arena モード。例:64 GB の PC で Q2_0 や IQ3_XXS)に効果があります。Strata のデータフォルダーにある設定ファイル `strata-.json`([場所](docs/INSTALL.md#where-things-are-stored))を開き、次を追加します: - -- **生成の高速化:** `"args"` リストに `"--adapt-async", "1"`。エキスパートキャッシュの更新が回答を止めずに補助スレッドで行われます。RTX 5070(Windows、Q2_0)での実測:生成 +4〜5%、コードや長文では +7〜10%。回答はデフォルトとわずかに異なる場合があります(実行ごとには同じです)。 -- **Windows でのプロンプト読み込みの高速化:** `"env"` ブロックに `"STRATA_PIN_BY_NEED": "1"`。Windows はGPU 用に RAM の約半分しか固定できないため、この設定で GPU が本当に必要とするエキスパートから先に固定します。RTX 5070 での実測:プロンプト読み込み +4.4%。 - -```json -"args": [ ..., "--adapt-async", "1" ], -"env": { "STRATA_PIN_BY_NEED": "1" } +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex ``` -変更後は Strata を再起動してください(`START-HERE.bat` または `./setup.sh`)。元に戻すには、2 つの項目を削除します。 +Windows では、インストール後に新しいターミナルを開きます。そのあと: + +```sh +strata launch +``` -## うまくいかないとき +画面の案内に従って、モデルをダウンロードして起動します。[ターミナルガイド](docs/TERMINAL_LAUNCH.md)。 -- **初回起動時に PC が応答しなくなる。** モデルの読み込み中は、一時的に応答しなくなることがあります。ウィンドウを閉じずにお待ちください。 - 10 分たっても応答しない場合は、PC を再起動して他のアプリを閉じてからやり直すか、モデルのサイズを小さくしてください。 -- **ダウンロードやインストールが途中で止まる。** `START-HERE.bat`(または `./setup.sh`)をもう一度実行してください。 - 中断したところから再開できます。 -- **動作が極端に遅く、ディスクのアクセスランプが点滅し続ける。または「the engine stopped unexpectedly」と表示される。** RAM の空き容量が不足しています。 - ブラウザーなど、RAM を多く使う他のアプリを閉じるか、小さいモデル(Q2_0 または IQ2_XS)を選んでください。 -- **ポート 8080 が使用中と表示される。** Strata がすでに起動しています。起動済みのウィンドウを探してください。 +
-その他の問題と対処方法は、[docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)をご覧ください。解決しない場合は -[Issue](https://github.com/Niko1221/Strata/issues) を作成し、Strata フォルダー内の `strata-.log` を添付してください。 -セキュリティ上の問題は、[SECURITY.md](SECURITY.md)の手順に従って非公開で報告してください。 +

+ モデルの動作、速度、メモリ、最近のリクエストを表示する Strata ターミナルアプリ +
動作中のモデルとハードウェアの状態を確認できます。 +

-## しくみ + -この規模のモデルは通常、数百ギガバイトの GPU メモリを搭載したサーバーで動かします。一方、手元のグラフィックカードのメモリは -12-24 GB 程度です。Strata は **PC 全体で処理を分担する** ことで、こうした環境でもモデルを動かせるようにしています。 -台所で、よく使うものは調理台に置き、それ以外は食品庫にしまっておくような仕組みです。 +[ソースからビルド](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [インストールガイド(全文)](docs/INSTALL.md) -

24,576 個のエキスパートのうち、よく使うものをグラフィックカードに配置。全エキスパートは RAM に、ルックアップテーブルは SSD に保持

+ -- **モデルは「エキスパート」と呼ばれる 24,576 個の小さな処理単位から構成されています。** 1 語の生成に必要なのは、このうち 10 個だけです。 -- **グラフィックカード** に、使用頻度の高い数千個のエキスパートを置きます。**RAM** にはすべてのエキスパートを保持し、 - **CPU** が残りの処理を並行して担当します。**SSD** には大きなルックアップテーブルを保存します。 +## ハードウェア -

小さな補助モデルが次の数語を予測し、大きなモデルがまとめて検証。正しい予測だけを採用する

+| 対応ハードウェア | ガイド | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 シリーズ** | [NVIDIA のセットアップ](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900、RX 9060 / 9070、AI PRO R9700** | [AMD のセットアップ](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · 試験的** | [RX 6000 のセットアップ](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Intel のセットアップ](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 以降** | [Mac のセットアップ](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo のセットアップ](docs/STRIX_HALO.md) | -- **予測してから検証:** 小さな補助モデルが次の数語を予測し、大きなモデルがまとめて検証します。 - 回答を変えずに、生成速度を 1.6-1.8 倍に高められます。 -- **長いテキストはまとめて読み込みます**(一度に最大 8,192 トークン)。読み込み速度は毎秒 1,000 トークンを超えます。 + -仕組みについては、[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md)で詳しく説明しています。各処理の詳細や測定値は、 -[技術資料](docs/DETAILS.md#how-it-works)と[論文](docs/paper/Strata-Paper.pdf)をご覧ください。 +## ツール -## クレジットとライセンス +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**。OpenAI 互換と Anthropic 互換の API を通じて、ほかのツールも使えます。 -使用しているモデルは、Qwen チームが開発した [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) です。 -[ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF)、UkisAI(Swift 1.5)、Unsloth が提供する圧縮版を利用しています。 -Strata は [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) の一部も使用しています。クレジットの一覧は -[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits)をご覧ください。Strata は [MIT License](LICENSE) で公開されていますが、一部の構成要素と -各モデルには、それぞれ別のライセンスが適用されます([ライセンスの詳細](docs/HOW_IT_WORKS.md#license))。 +**`strata connect`** を実行すると、お使いのツールの設定方法が表示されます。[接続ガイド](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect)。 + + + + + + +## ヘルプ + +[すべてのガイド](docs) · [トラブルシューティング](docs/TROUBLESHOOTING.md) · [不具合を報告](https://github.com/Niko1221/Strata/issues/new/choose) · +[ベンチマーク](docs/COMMUNITY_BENCHMARKS.md) · [仕組み](docs/HOW_IT_WORKS.md) · [貢献する](CONTRIBUTING.md) ## Strata を支援する -Strata は無料で使えるオープンソースソフトウェアです。役に立ったら、開発へのご支援をお願いします。 +**ローカル AI をみんなに開かれたものに。** コーヒー1杯が、開発と、より多くのハードウェアでのテストの支えになります。 + +Buy Me a Coffee: Strata を支援する + +[MIT ライセンス](LICENSE) · [クレジットとモデルのライセンス](docs/HOW_IT_WORKS.md#credits) · [プライバシー](docs/SAFETY.md) + + + +AI ツールと自動リーダー向け: 技術リファレンス · セットアップ手順 -

Buy Me A Coffee

+**スポンサー、ハードウェア提携、共同開発のご相談:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/README.md b/README.md index 81be3848b13..f46c4e87416 100644 --- a/README.md +++ b/README.md @@ -1,243 +1,195 @@ -

Strata

+

+ + + Strata + +

-**English** · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · [Português](README.pt-BR.md) +

Run powerful AI on your own computer.

+

Chat, code and work with images, locally.

-

Run a 125-billion-parameter AI model on your own gaming PC
-NVIDIA or AMD graphics card (12 GB or more) · Windows or Linux · free and open source

+

+ Models · Install · + Hardware · Tools · + Help · Support +

-

A voxel pagoda garden that Strata's model wrote, running in the browser
-A voxel pagoda garden, 1 shot prompt running on an RTX 5070 with Strata (IQ3_S, 128K context) · -full video (49 s)

+

+ Download Strata + MIT license + Support Strata on Buy Me a Coffee +

-Strata runs **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** on a normal PC. This is a -large, smart AI model that usually needs a server. It chats, writes code, reads pictures and works with your apps -and coding agents. Nothing leaves your PC. +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

-## How fast is it? +**Free, open source, and yours to run.** Use Strata on your desktop or with your favorite coding tools. No account needed. -We measured it on two ordinary gaming PCs. A token is about ¾ of a word. +## Models -- **Writes answers:** how fast the reply appears in a short chat. 60 tokens per second is faster than you can read. -- **Reads your prompt:** how fast it takes in what you send (here a 32K-token document, code or chat history). +We recommend **ISTA-DASLab first**, then **Unsloth** and other providers, where a compatible model fits. - - - -
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM
+
+  Qwen3.8-Flash-Next -| Size | Writes answers | Reads your prompt | +| Provider | Choices | +| --- | --- | +| **ISTA-DASLab · recommended** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) for coding. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Lower memory use but slower. | +| **Other options** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Compare sizes, memory needs and compatibility](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. These are the currently documented packs for this model. + +[Model guide and compatibility](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +In the **desktop app** and the **Terminal**. What does not fit in memory is read from your SSD, so it needs a lot of free +disk space. + +| Set (ISTA-DAS) | Download | Free disk needed | | --- | ---: | ---: | -| **Q2_0** | 94 tokens/s | 2,650 tokens/s | -| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | -| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | -| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | -| **Coder** | 55 tokens/s | 2,180 tokens/s | +| 1.75 bpw | 239 GB | about 245 GB | +| 2.00 bpw | 257 GB | about 265 GB | +| 2.25 bpw | 274 GB | about 280 GB | +| ISTA-DAS Coder (half of the experts removed) | 191 GB | about 197 GB | + +Runs on NVIDIA RTX 30, 40 and 50 series (Windows and Linux), AMD Radeon AI PRO R9700 (Linux), AMD Ryzen AI Max — Strix Halo +(Windows), and Apple Silicon Macs with 64 GB or more, text only ([Mac](docs/DEEPSEEK_MAC.md)). Setup downloads the files and the DeepSeek engine, then starts the model. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` -
+Measured with the 2.00 bpw set on Strata 0.2.5 (Strix Halo: 0.2.7). Output is the speed of the answer, prompt is how fast Strata reads your input. -| Size | Writes answers | Reads your prompt | +| Hardware | Output | Prompt | | --- | ---: | ---: | -| **Q2_0** | 60 tokens/s | 1,160 tokens/s | -| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | -| **Coder** | 44 tokens/s | 1,420 tokens/s | +| RTX 5070 12 GB, 64 GB RAM | 4 to 6 tokens/s | about 110 tokens/s (4K) | +| RTX 3060 12 GB, 46 GB RAM | 9 to 11 tokens/s | about 155 tokens/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB RAM | 21 to 25 tokens/s | 320 to 360 tokens/s (8K) | +| 4x Radeon AI PRO R9700 | 74 to 77 tokens/s | 400 to 450 tokens/s (8K) | +| Ryzen AI Max+ 395 (Strix Halo), 128 GB unified | 19 to 21 tokens/s (code), 11 (chat) | 87 tokens/s (4K), 125 tokens/s (8K) | -
+[Memory, disk and details](docs/DEEPSEEK41.md) · [Release notes](https://github.com/Niko1221/Strata/releases) -NVIDIA: Q2_0 with engine 0.1.36, the other rows with 0.1.26 (4K answers, 32K prompts). The full tables are in -[DETAILS.md](docs/DETAILS.md#speed-measured). A card with more VRAM is faster: an RTX 3090 (24 GB) should write -about 100-140 tokens per second. Long chats and other cards: [speed of each model](docs/MODELS.md#how-fast-is-each-size), -[community results](docs/COMMUNITY_BENCHMARKS.md). + -

Buy Me A Coffee
-Strata is free. If it runs well on your PC, a coffee keeps the work on it going.

+ -## What you need +Not sure what fits? [Choose a model for your computer](docs/MODELS.md#pick-by-memory). -| | | -| --- | --- | -| **Graphics card** | **NVIDIA** GeForce RTX 20, 30, 40 or 50 series, or **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 or RX 6800 / 6900 series. It needs **12 GB of VRAM or more**. | -| **RAM** | 32 GB or more. Your RAM decides [which model](#which-model-should-i-pick) fits. 64 GB runs every size. | -| **Disk** | About 80 GB free. Use an SSD if you can: the first start is much faster. | -| **System** | Windows 10 / 11 or Linux, and a current graphics driver from NVIDIA or AMD. | +## Install -The installer sets up everything else. Two or three cards can share the model ([multi-GPU](docs/MULTI_GPU.md)). + -Experimental, written and tested by community members on their own machines: +### Desktop app -- **Older graphics cards** (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT): [Older GPUs](docs/OLDER_GPUS.md). -- **Intel Arc**, built from source on Linux: [Intel Arc](docs/INTEL_ARC.md). -- **Apple Silicon Macs (M1 to M5)**, built from source by `./setup.sh` (the Metal engine): [Mac](docs/MAC.md). -- **AMD Ryzen AI Max (Strix Halo)**, built from source on Linux: [Strix Halo](docs/STRIX_HALO.md). -- **Older processors without AVX2**: they work, but slowly. [Older CPUs](docs/INSTALL.md#older-cpus-experimental). +**[Download Strata for Windows, Linux or Mac →](https://github.com/Niko1221/Strata/releases/latest)** -The full list: [docs/INSTALL.md](docs/INSTALL.md#what-you-need). +Install the app, choose a model, and start chatting. There is one installer for each system. On first start the app +downloads the engine for your graphics card. [Help with the installer](docs/INSTALL.md#the-app). -## Install +Files: `Strata-0.2.9-windows-x64-setup.exe` · `Strata-0.2.9-linux-x86_64.AppImage` · `Strata-0.2.9-macos-arm64.dmg` -### Let your AI set it up +

+ Strata desktop app with a chat and live code preview side by side +
Chat, files and a live preview in one window. +

-Do you use an AI coding assistant (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Paste this into it: + -```text -Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +### Terminal app + +Prefer the terminal? Install Strata, then run **`strata launch`**. + +
+Install commands + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh ``` -It checks your graphics card, RAM and disk and picks the model that fits. Then it installs and starts it and tells -you how to connect your apps. AI tools can also install, start and stop Strata through its -[MCP server](docs/MCP_SERVER.md). - -### Or do it yourself - -[Download Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) and unzip it (or `git clone` it). -**Windows:** double-click **`START-HERE.bat`**. **Linux:** run **`./setup.sh`** in the Strata folder. - -**Mac (Apple Silicon, M1 to M5, macOS 15 or newer):** install Apple's Command Line Tools once -(`xcode-select --install` in Terminal; Xcode itself is not needed). Then open Terminal in the Strata folder and run -**`./setup.sh`**. It builds the Mac engine on your Mac (about 7 minutes), asks the same questions, downloads the model -and starts it. Next time, `./setup.sh` starts it right away. Which size fits your Mac and how fast it is: -[docs/MAC.md](docs/MAC.md). - -The steps are the same for NVIDIA and AMD. The installer finds your card and sets up the right engine for it. It -asks you a few questions: - -- which model and which size, -- how much context (how much text the model keeps in mind), -- whether it should read pictures. - -Press Enter each time for the recommended answer. Then it downloads the model (about 70 GB) and starts it. If the -download stops, run it again: it continues where it left off. Your browser opens the Strata app at -`http://127.0.0.1:8080`. - -> **While the model starts, your PC can be slow or stop responding for 1-3 minutes** (longest the first time). -> Strata loads 35-55 GB into your RAM and locks part of it for the graphics card. This is normal. Wait, and don't -> close the window. The window shows what Strata is doing. - -**Next time**, run `START-HERE.bat` (or `./setup.sh`) again. It starts right away and downloads nothing twice. Close -its window to stop the model. `UPDATE.bat` (`./update.sh`) updates Strata without starting it. Updating, Docker, -several cards, where the files go and every option: [docs/INSTALL.md](docs/INSTALL.md). - -**Is it fast on your PC?** Run `BENCH.bat` (`./bench.sh`): about 5-10 minutes, it measures chat, 4K/16K prompts and an agent-style session with your own settings and writes a report to share ([how](docs/COMMUNITY_BENCHMARKS.md#run-the-benchmark)). - -## Which model should I pick? - -The installer recommends one for your RAM. The same model comes in several sizes, compressed more or less. Smaller -sizes are faster. Larger sizes are a bit smarter. - -| Your RAM | Take | Why | -| --- | --- | --- | -| **32 GB** | **Coder** | it fits 32 GB, and it is made for code (with a 24 GB card, Q2_0 and IQ2_XS run too) | -| **48 GB** | **IQ2_XS** (or Q2_0, the fastest) | the larger sizes do not fit | -| **64 GB** | **IQ2_XS** (recommended), or IQ3_XXS / IQ3_S | every size fits; IQ3_S is the best and the slowest | -| **96 GB or more** | **IQ3_S**, or Unsloth's UD-IQ4_XS (~4-bit) | room for the largest sizes with everything else open | - -- **[Coder](docs/MODELS.md#coder):** a coding version with half of the experts removed. It reaches 91% of the full - model's SWE-bench Verified score (measured by its authors) and fits 32 GB of RAM. It is weaker outside code, - including Chinese and other CJK text (#438). For those, take Q2_0, IQ2_XS or IQ3_S, which keep every expert. -- **[Swift 1.5](docs/MODELS.md#swift-15):** a fine-tune that thinks for a much shorter time before it answers. You - get the answer sooner, at about the same quality. -- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** Unsloth's ~4-bit version, between IQ3_S and - UD-Q4_K_XL in quality. A 94 GB download. With less than ~80 GB of RAM, Strata reads part of it from the SSD - while it answers, so it is slower there (an NVMe SSD helps). -- **[Unsloth UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL and Q8_0](docs/MODELS.md#unsloths-files-ud-iq4_xs-to-q8_0):** - 4- to 8-bit, closer to the full model (93-95% the same next token as Q8_0). Fast where every expert fits in RAM - (~88 GB for UD-Q4_K_XL up to ~136 GB for Q8_0); with less RAM Strata reads part of them from the SSD while it - answers, which is much slower (7-8.5 tokens/s for UD-Q4_K_XL on a 64 GB PC). -- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** you set it up by hand. It is - not in the installer's menu. - -Sizes, downloads and what fits where: [docs/MODELS.md](docs/MODELS.md). To add another model later, run -`SETUP.bat` (Linux: `./setup.sh --setup`). - -## Using it - -

The Strata app's Monitor tab next to a coding agent
-The Strata app's Monitor (left) while a coding agent writes the pagoda garden from the video (right)

- -- **In the browser:** open `http://127.0.0.1:8080`. It has **Chat**, a live **Monitor** of the model and your - GPU/CPU/RAM, and **About** with the settings and addresses. -- **Your apps and coding agents:** add an "OpenAI-compatible" provider with the base URL - **`http://127.0.0.1:8080/v1`**. Any API key and any model name work. - - Apps that use Anthropic's API: `http://127.0.0.1:8080/v1/messages` (Claude Code: - `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). - - Codex CLI and other apps that use the OpenAI Responses API: `/v1/responses` - ([setup](docs/DETAILS.md#the-responses-api-and-codex-cli)). -- **Thinking:** choose **off, low, medium or high** in the chat menu or in your app's "reasoning effort". Off is the - fastest. High is best for hard questions. -- **Pictures:** say yes to "Images?" in setup. Then click **Picture** in the chat, or attach pictures in your app. - AMD cards read pictures on Linux through the processor; on Windows they can't yet. -- **From your phone or another PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `. Always set a key. -- **One request at a time:** by default Strata answers one request, and the others wait. To answer several at once, - set `"parallel": 2` ([BATCHING.md](docs/BATCHING.md)). On a 12 GB card this makes each answer slower. -- **Long prompts:** Strata reads the first message of a chat in full, about 1 minute per 30,000 tokens. Follow-up - messages start in seconds. - -More: [where your chats are stored](docs/INSTALL.md#where-things-are-stored), [the API](docs/DETAILS.md#using-it). - -### Optional: more speed on one card when the whole model fits in RAM - -Two opt-in settings (by RubenTorney, #1904 and #1905). They help when you run one graphics card and your RAM holds -every expert (Strata's arena mode, for example Q2_0 or IQ3_XXS on a 64 GB PC). Open your config, -`strata-.json` in the Strata data folder ([where](docs/INSTALL.md#where-things-are-stored)), and add: - -- **Faster decode:** `"--adapt-async", "1"` to the `"args"` list. The expert cache then updates on a helper thread - instead of pausing the answer. Measured on an RTX 5070 (Windows, Q2_0): +4-5% decode, +7-10% on code and long - documents. Answers can differ slightly from the default (they stay the same from run to run). -- **Faster prompt reading on Windows:** `"STRATA_PIN_BY_NEED": "1"` in the `"env"` block. Windows can lock only about - half the RAM for the graphics card; this locks the experts the card actually needs first. Measured on the RTX 5070: - +4.4% prompt reading. - -```json -"args": [ ..., "--adapt-async", "1" ], -"env": { "STRATA_PIN_BY_NEED": "1" } +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +On Windows, open a new terminal afterwards. Then: + +```sh +strata launch ``` -Restart Strata (`START-HERE.bat` or `./setup.sh`) after the change. To undo, remove the two entries. +Follow the prompts to download and start a model. [Terminal guide](docs/TERMINAL_LAUNCH.md). -## Something went wrong? +
-- **My PC froze the first time Strata started.** This is normal while it loads the model. Wait, and don't close the - window. Still frozen after 10 minutes? Restart the PC, close other programs and try again, or pick a smaller size. -- **It stopped while downloading or installing.** Run `START-HERE.bat` (or `./setup.sh`) again. It continues where - it stopped. -- **It's very slow and the disk light keeps blinking, or it says "the engine stopped unexpectedly".** Your PC does - not have enough free RAM. Close other programs (browsers use a lot), or pick a smaller size (Q2_0 or IQ2_XS). -- **It says port 8080 is already in use.** Strata is already running. Look for its window. +

+ Strata terminal app showing model activity, speed, memory and recent requests +
Watch your model and hardware while it runs. +

-More problems and their fixes: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Still stuck? Open an -[issue](https://github.com/Niko1221/Strata/issues) and attach `strata-.log` from the Strata folder. Found a -security problem? Report it privately: [SECURITY.md](SECURITY.md). + -## How does it work? +[Build from source](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Full install guide](docs/INSTALL.md) -Models like this one usually run on servers with hundreds of gigabytes of graphics memory. Your graphics card has -12-24 GB. Strata makes the model fit by **sharing the work across your whole PC**. Think of a kitchen: the things -you use all the time stay on the counter, and the rest waits in the pantry. + -

The model's 24,576 experts: the busiest on the graphics card, all of them in RAM, a lookup table on the SSD

+## Hardware -- **The model is a team of 24,576 small specialists ("experts").** Each word needs only 10 of them. -- **Your graphics card** keeps the few thousand experts that are used most often. **Your RAM** holds all of them, - and **your processor** works on the rest at the same time. **Your SSD** holds a big lookup table. +| Supported hardware | Guide | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 series** | [NVIDIA setup](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [AMD setup](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · experimental** | [RX 6000 setup](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Intel setup](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 or newer** | [Mac setup](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo setup](docs/STRIX_HALO.md) | +| **NVIDIA DGX Spark · Linux** | [DGX Spark setup](docs/DGX_SPARK_LINUX.md) | + + -

A small helper guesses the next words; the big model checks them all at once and keeps the right ones

+## Tools -- **Guess, then check:** a small helper guesses the next few words. The big model checks them all at once. You get - the same answer, 1.6-1.8x sooner. -- **Long texts are read in big pieces** (up to 8,192 tokens at a time), at over 1,000 tokens per second. +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, and more through the OpenAI- and Anthropic-compatible APIs. -The longer explanation: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Every part and its numbers: -[the details](docs/DETAILS.md#how-it-works) and the [paper](docs/paper/Strata-Paper.pdf). +Run **`strata connect`** to see setup instructions for your tool. [Connection guide](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). -## Credits and license + + + + -The model is [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team. It was -compressed by [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) -and Unsloth. Strata uses parts of [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). All credits: -[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata is open source under the [MIT License](LICENSE). A few -parts and every model have their own licenses ([which ones](docs/HOW_IT_WORKS.md#license)). +## Help + +[All guides](docs) · [Troubleshooting](docs/TROUBLESHOOTING.md) · [Report a bug](https://github.com/Niko1221/Strata/issues/new/choose) · +[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [How it works](docs/HOW_IT_WORKS.md) · [Contribute](CONTRIBUTING.md) ## Support Strata -Strata is free and open source. If it is useful to you, you can support its development: +**Help keep local AI open to everyone.** A coffee helps fund development and testing on more hardware. + +Buy Me a Coffee: support Strata + +[MIT license](LICENSE) · [Credits and model licenses](docs/HOW_IT_WORKS.md#credits) · [Privacy](docs/SAFETY.md) + + + +For AI tools and automated readers: technical reference · setup instructions. + +**Sponsorships, hardware partnerships or collaborations:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). -

Buy Me A Coffee

diff --git a/README.pl.md b/README.pl.md new file mode 100644 index 00000000000..89c19247716 --- /dev/null +++ b/README.pl.md @@ -0,0 +1,192 @@ +

+ + + Strata + +

+ +

Uruchom potężną sztuczną inteligencję na własnym komputerze.

+

Rozmawiaj, programuj i pracuj z obrazami — lokalnie.

+ +

+ Modele · Instalacja · + Sprzęt · Narzędzia · + Pomoc · Wsparcie +

+ +

+ Pobierz Stratę + Licencja MIT + Wesprzyj Stratę na Buy Me a Coffee +

+ +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

+ +**Bezpłatna, z otwartym kodem źródłowym i do uruchomienia u siebie.** Używaj Straty na swoim komputerze albo razem z ulubionymi narzędziami do programowania. Konto nie jest potrzebne. + +## Modele + +Najpierw polecamy **ISTA-DASLab**, potem **Unsloth** i innych dostawców — o ile zgodny model mieści się w pamięci. + +
+  Qwen3.8-Flash-Next + +| Dostawca | Do wyboru | +| --- | --- | +| **ISTA-DASLab · polecany** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) do programowania. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Zużywa mniej pamięci, ale działa wolniej. | +| **Inne opcje** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Porównaj rozmiary, wymagania pamięciowe i zgodność](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. To obecnie udokumentowane pakiety dla tego modelu. + +[Przewodnik po modelu i zgodność](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +W **aplikacji na komputer** i w **Terminalu**. To, co nie mieści się w pamięci, jest czytane z dysku SSD, więc potrzebujesz +dużo wolnego miejsca na dysku. + +| Zestaw (ISTA-DAS) | Do pobrania | Potrzebne wolne miejsce | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | około 245 GB | +| 2.00 bpw | 257 GB | około 265 GB | +| 2.25 bpw | 274 GB | około 280 GB | + +Działa na kartach NVIDIA RTX serii 30, 40 i 50 (Windows i Linux), AMD Radeon AI PRO R9700 (Linux) oraz AMD Ryzen AI Max — Strix Halo +(Windows). Instalacja pobiera pliki i silnik DeepSeek, a potem uruchamia model. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` + +Zmierzone na zestawie 2.00 bpw w Strata 0.2.5 (Strix Halo: 0.2.7). „Wyjście” to szybkość odpowiedzi, „prompt” — jak szybko Strata czyta twój tekst. + +| Sprzęt | Wyjście | Prompt | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB RAM | 4–6 tokenów/s | około 110 tokenów/s (4K) | +| RTX 3060 12 GB, 46 GB RAM | 9–11 tokenów/s | około 155 tokenów/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB RAM | 21–25 tokenów/s | 320–360 tokenów/s (8K) | +| 4x Radeon AI PRO R9700 | 74–77 tokenów/s | 400–450 tokenów/s (8K) | +| Ryzen AI Max+ 395 (Strix Halo), 128 GB pamięci współdzielonej | 19–21 tokenów/s (kod), 11 (czat) | 87 tokenów/s (4K), 125 tokenów/s (8K) | + +[Pamięć, dysk i szczegóły](docs/DEEPSEEK41.md) · [Informacje o wydaniach](https://github.com/Niko1221/Strata/releases) + +
+ + + +Nie wiesz, co się zmieści? [Wybierz model do swojego komputera](docs/MODELS.md#pick-by-memory). + +## Instalacja + + + +### Aplikacja na komputer + +**[Pobierz Stratę dla Windows, Linuxa lub Maca →](https://github.com/Niko1221/Strata/releases/latest)** + +Zainstaluj aplikację, wybierz model i zacznij rozmawiać. Dla każdego systemu jest jeden instalator. Przy pierwszym +uruchomieniu aplikacja pobiera silnik dla twojej karty graficznej. [Pomoc z instalatorem](docs/INSTALL.md#the-app). + +Pliki: `Strata-0.2.9-windows-x64-setup.exe` · `Strata-0.2.9-linux-x86_64.AppImage` · `Strata-0.2.9-macos-arm64.dmg` + +

+ Aplikacja Strata na komputer: czat i podgląd kodu na żywo obok siebie +
Czat, pliki i podgląd na żywo w jednym oknie. +

+ + + +### Aplikacja Terminal + +Wolisz terminal? Zainstaluj Stratę, a potem uruchom **`strata launch`**. + +
+Polecenia instalacji + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +``` + +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +W Windows otwórz potem nowe okno terminala. Następnie: + +```sh +strata launch +``` + +Postępuj zgodnie z podpowiedziami, aby pobrać i uruchomić model. [Przewodnik po Terminalu](docs/TERMINAL_LAUNCH.md). + +
+ +

+ Aplikacja Terminal Straty pokazująca aktywność modelu, szybkość, pamięć i ostatnie zapytania +
Obserwuj model i sprzęt w trakcie pracy. +

+ + + +[Budowanie ze źródeł](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Pełny przewodnik instalacji](docs/INSTALL.md) + + + +## Sprzęt + +| Obsługiwany sprzęt | Przewodnik | +| --- | --- | +| **NVIDIA GeForce RTX serii 20 / 30 / 40 / 50** | [Konfiguracja NVIDIA](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Konfiguracja AMD](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · eksperymentalnie** | [Konfiguracja RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Konfiguracja Intel](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 lub nowszy** | [Konfiguracja Mac](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Konfiguracja Strix Halo](docs/STRIX_HALO.md) | + + + +## Narzędzia + +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw** i inne — przez API zgodne z OpenAI i Anthropic. + +Uruchom **`strata connect`**, aby zobaczyć instrukcję konfiguracji dla swojego narzędzia. [Przewodnik po połączeniach](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). + + + + + + +## Pomoc + +[Wszystkie przewodniki](docs) · [Rozwiązywanie problemów](docs/TROUBLESHOOTING.md) · [Zgłoś błąd](https://github.com/Niko1221/Strata/issues/new/choose) · +[Testy wydajności](docs/COMMUNITY_BENCHMARKS.md) · [Jak to działa](docs/HOW_IT_WORKS.md) · [Współtworzenie](CONTRIBUTING.md) + +## Wesprzyj Stratę + +**Pomóż zachować lokalną sztuczną inteligencję otwartą dla wszystkich.** Kawa pomaga finansować rozwój i testy na większej liczbie sprzętu. + +Buy Me a Coffee: wesprzyj Stratę + +[Licencja MIT](LICENSE) · [Podziękowania i licencje modeli](docs/HOW_IT_WORKS.md#credits) · [Prywatność](docs/SAFETY.md) + + + +Dla narzędzi AI i automatycznych czytników: dokumentacja techniczna · instrukcja instalacji. + +**Sponsoring, partnerstwa sprzętowe i współpraca:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/README.pt-BR.md b/README.pt-BR.md index 72961127f04..439ac607de7 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -1,234 +1,188 @@ -

Strata

+

+ + + Strata + +

-[English](README.md) · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · **Português** +

IA poderosa no seu próprio computador.

+

Converse, programe e trabalhe com imagens, localmente.

-

Rode um modelo de IA de 125 bilhões de parâmetros no seu próprio PC gamer
-Placa de vídeo NVIDIA ou AMD (12 GB ou mais) · Windows ou Linux · gratuito e de código aberto

+

+ Modelos · Instalação · + Hardware · Ferramentas · + Ajuda · Apoiar +

-

Um jardim com pagode em voxels que o modelo do Strata escreveu, rodando no navegador
-Um jardim com pagode em voxels, feito com um único prompt numa RTX 5070 com o Strata (IQ3_S, contexto de 128K) · -vídeo completo (49 s)

+

+ Baixar o Strata + Licença MIT + Apoie o Strata no Buy Me a Coffee +

-O Strata roda o **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** num PC comum. É um modelo -de IA grande e inteligente que normalmente precisa de um servidor. Ele conversa, escreve código, entende imagens e -funciona com seus apps e agentes de programação. Nada sai do seu PC. +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

-## Qual é a velocidade? +**Gratuito, de código aberto e seu para executar.** Use o Strata no desktop ou com suas ferramentas de programação favoritas. Não precisa de conta. -Medimos em dois PCs gamer comuns. Um token equivale a cerca de ¾ de uma palavra. +## Modelos -- **Escreve respostas:** a velocidade com que a resposta aparece numa conversa curta. 60 tokens por segundo é mais rápido do que você consegue ler. -- **Lê seu prompt:** a velocidade com que ele absorve o que você envia (aqui, um documento, código ou histórico de conversa de 32K tokens). +Recomendamos **primeiro a ISTA-DASLab**, depois a **Unsloth** e outros provedores, quando um modelo compatível cabe na memória. - - - -
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB de RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB de RAM
+
+  Qwen3.8-Flash-Next -| Tamanho | Escreve respostas | Lê seu prompt | +| Provedor | Opções | +| --- | --- | +| **ISTA-DASLab · recomendado** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) para programar. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Usa menos memória, mas é mais lento. | +| **Outras opções** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Compare tamanhos, necessidades de memória e compatibilidade](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Esses são os pacotes documentados atualmente para este modelo. + +[Guia do modelo e compatibilidade](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +No **aplicativo de desktop** e no **Terminal**. O que não cabe na memória é lido do seu SSD, por isso é preciso muito espaço livre em disco. + +| Conjunto (ISTA-DAS) | Download | Espaço livre necessário | | --- | ---: | ---: | -| **Q2_0** | 94 tokens/s | 2,650 tokens/s | -| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | -| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | -| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | -| **Coder** | 55 tokens/s | 2,180 tokens/s | +| 1.75 bpw | 239 GB | cerca de 245 GB | +| 2.00 bpw | 257 GB | cerca de 265 GB | +| 2.25 bpw | 274 GB | cerca de 280 GB | + +Roda em NVIDIA RTX 30, 40 e 50 (Windows e Linux) e em AMD Radeon AI PRO R9700 (Linux). A instalação baixa os arquivos e o motor do DeepSeek e depois inicia o modelo. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` -
+Medido com o conjunto de 2.00 bpw no Strata 0.2.5. “Saída” é a velocidade da resposta; “Prompt” é a rapidez com que o Strata lê o seu texto. -| Tamanho | Escreve respostas | Lê seu prompt | +| Hardware | Saída | Prompt | | --- | ---: | ---: | -| **Q2_0** | 60 tokens/s | 1,160 tokens/s | -| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | -| **Coder** | 44 tokens/s | 1,420 tokens/s | +| RTX 5070 12 GB, 64 GB de RAM | 4 a 6 tokens/s | cerca de 110 tokens/s (4K) | +| RTX 3060 12 GB, 46 GB de RAM | 9 a 11 tokens/s | cerca de 155 tokens/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 a 25 tokens/s | 320 a 360 tokens/s (8K) | +| 4x Radeon AI PRO R9700 | 74 a 77 tokens/s | 400 a 450 tokens/s (8K) | -
+[Memória, disco e detalhes](docs/DEEPSEEK41.md) · [Notas da versão](https://github.com/Niko1221/Strata/releases) -NVIDIA: Q2_0 com o engine 0.1.36, as outras linhas com 0.1.26 (respostas de 4K, prompts de 32K). As tabelas -completas estão em [DETAILS.md](docs/DETAILS.md#speed-measured). Uma placa com mais VRAM é mais rápida: uma -RTX 3090 (24 GB) deve escrever cerca de 100-140 tokens por segundo. Conversas longas e outras placas: -[velocidade de cada modelo](docs/MODELS.md#how-fast-is-each-size), [resultados da comunidade](docs/COMMUNITY_BENCHMARKS.md). + -

Buy Me A Coffee
-O Strata é gratuito. Se ele roda bem no seu PC, um café ajuda a manter o trabalho nele.

+ -## Do que você precisa +Não sabe o que cabe? [Escolha um modelo para o seu computador](docs/MODELS.md#pick-by-memory). -| | | -| --- | --- | -| **Placa de vídeo** | **NVIDIA** GeForce RTX séries 20, 30, 40 ou 50, ou **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 ou séries RX 6800 / 6900. Ela precisa de **12 GB de VRAM ou mais**. | -| **RAM** | 32 GB ou mais. Sua RAM decide [qual modelo](#qual-modelo-devo-escolher) cabe. Com 64 GB, roda qualquer tamanho. | -| **Disco** | Cerca de 80 GB livres. Use um SSD se puder: a primeira inicialização fica bem mais rápida. | -| **Sistema** | Windows 10 / 11 ou Linux, e um driver de vídeo atualizado da NVIDIA ou da AMD. | +## Instalação -O instalador cuida de todo o resto. Duas ou três placas podem dividir o modelo ([multi-GPU](docs/MULTI_GPU.md)). + -Experimental, escrito e testado por membros da comunidade nas próprias máquinas: +### Aplicativo de desktop -- **Placas de vídeo mais antigas** (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT): [Older GPUs](docs/OLDER_GPUS.md). -- **Intel Arc**, compilado a partir do código-fonte no Linux: [Intel Arc](docs/INTEL_ARC.md). -- **AMD Ryzen AI Max (Strix Halo)**, compilado a partir do código-fonte no Linux: [Strix Halo](docs/STRIX_HALO.md). -- **Processadores mais antigos sem AVX2**: funcionam, mas devagar. [Older CPUs](docs/INSTALL.md#older-cpus-experimental). +**[Baixar o Strata para Windows, Linux ou Mac →](https://github.com/Niko1221/Strata/releases/latest)** -A lista completa: [docs/INSTALL.md](docs/INSTALL.md#what-you-need). +Instale o aplicativo, escolha um modelo e comece a conversar. Há um instalador por sistema. Na primeira vez que abre, o aplicativo baixa o motor da sua placa de vídeo. [Ajuda com o instalador](docs/INSTALL.md#the-app). -## Instalação +Arquivos: `Strata-0.2.9-windows-x64-setup.exe` · `Strata-0.2.9-linux-x86_64.AppImage` · `Strata-0.2.9-macos-arm64.dmg` -### Deixe sua IA instalar +

+ Aplicativo de desktop do Strata com um chat e uma prévia do código ao vivo lado a lado +
Chat, arquivos e prévia ao vivo em uma só janela. +

-Você usa um assistente de programação com IA (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Cole isto nele: + -```text -Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +### Aplicativo de Terminal + +Prefere o terminal? Instale o Strata e execute **`strata launch`**. + +
+Comandos de instalação + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh ``` -Ele verifica sua placa de vídeo, RAM e disco e escolhe o modelo que cabe. Depois instala, inicia e explica como -conectar seus apps. Ferramentas de IA também podem instalar, iniciar e parar o Strata pelo -[servidor MCP](docs/MCP_SERVER.md) dele. - -### Ou faça você mesmo - -[Baixe o Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) e descompacte (ou use `git clone`). -**Windows:** clique duas vezes em **`START-HERE.bat`**. **Linux:** rode **`./setup.sh`** na pasta do Strata. - -**Mac (Apple Silicon, M1 a M5, macOS 15 ou mais recente):** instale uma vez as Command Line Tools da Apple (`xcode-select --install` no Terminal; o Xcode em si não é necessário). Depois abra o Terminal na pasta do Strata e rode **`./setup.sh`**. Ele compila o motor do Mac no seu Mac (uns 7 minutos), faz as mesmas perguntas, baixa o modelo e o inicia. Da próxima vez, `./setup.sh` inicia na hora. Qual tamanho cabe no seu Mac e qual a velocidade: [docs/MAC.md](docs/MAC.md). - -Os passos são os mesmos para NVIDIA e AMD. O instalador encontra sua placa e configura o engine certo para ela. -Ele faz algumas perguntas: - -- qual modelo e qual tamanho, -- quanto contexto (quanto texto o modelo guarda na memória), -- se ele deve entender imagens. - -Aperte Enter em cada uma para usar a resposta recomendada. Depois ele baixa o modelo (cerca de 70 GB) e o inicia. -Se o download parar, rode de novo: ele continua de onde parou. Seu navegador abre o app do Strata em -`http://127.0.0.1:8080`. - -> **Enquanto o modelo inicia, seu PC pode ficar lento ou parar de responder por 1-3 minutos** (mais na primeira vez). -> O Strata carrega 35-55 GB na sua RAM e reserva parte dela para a placa de vídeo. Isso é normal. Espere e não -> feche a janela. A janela mostra o que o Strata está fazendo. - -**Da próxima vez**, rode `START-HERE.bat` (ou `./setup.sh`) de novo. Ele inicia na hora e não baixa nada duas -vezes. Feche a janela para parar o modelo. `UPDATE.bat` (`./update.sh`) atualiza o Strata sem iniciá-lo. -Atualização, Docker, várias placas, onde ficam os arquivos e todas as opções: [docs/INSTALL.md](docs/INSTALL.md). - -## Qual modelo devo escolher? - -O instalador recomenda um de acordo com sua RAM. O mesmo modelo vem em vários tamanhos, mais ou menos comprimidos. -Os tamanhos menores são mais rápidos. Os maiores são um pouco mais inteligentes. - -| Sua RAM | Escolha | Por quê | -| --- | --- | --- | -| **32 GB** | **Coder** | cabe em 32 GB e é feito para código (com uma placa de 24 GB, Q2_0 e IQ2_XS também rodam) | -| **48 GB** | **IQ2_XS** (ou Q2_0, o mais rápido) | os tamanhos maiores não cabem | -| **64 GB** | **IQ2_XS** (recomendado), ou IQ3_XXS / IQ3_S | todos os tamanhos cabem; IQ3_S é o melhor e o mais lento | -| **96 GB ou mais** | **IQ3_S**, ou o UD-IQ4_XS da Unsloth (~4-bit) | espaço para os maiores tamanhos com todo o resto aberto | - -- **[Coder](docs/MODELS.md#coder):** uma versão para programação com metade dos experts removida. Ela alcança 91% - da pontuação do modelo completo no SWE-bench Verified (medido pelos autores) e cabe em 32 GB de RAM. É mais fraca - fora do código, inclusive em chinês e outros textos CJK (#438). Para isso, escolha Q2_0, IQ2_XS ou IQ3_S, que - mantêm todos os experts. -- **[Swift 1.5](docs/MODELS.md#swift-15):** um fine-tune que pensa por bem menos tempo antes de responder. Você - recebe a resposta mais cedo, com quase a mesma qualidade. -- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** a versão de ~4 bits da Unsloth, entre IQ3_S e - UD-Q4_K_XL em qualidade. Um download de 94 GB. Com menos de ~80 GB de RAM, o Strata lê uma parte dele do SSD - enquanto responde, então ali ele fica mais lento (um SSD NVMe ajuda). -- **[Unsloth UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL e Q8_0](docs/MODELS.md#unsloths-files-ud-iq4_xs-to-q8_0):** de 4 a 8 bits, mais próximos do modelo - completo (93-95% o mesmo próximo token que o Q8_0). Rápidos quando todos os especialistas cabem na RAM (~88 GB para - o UD-Q4_K_XL até ~136 GB para o Q8_0); com menos RAM, o Strata lê uma parte do SSD enquanto responde, o que é bem - mais lento (7-8.5 tokens/s para o UD-Q4_K_XL num PC com 64 GB). -- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** você configura à mão. Ele - não está no menu do instalador. - -Tamanhos, downloads e o que cabe onde: [docs/MODELS.md](docs/MODELS.md). Para adicionar outro modelo depois, rode -`SETUP.bat` (Linux: `./setup.sh --setup`). - -## Como usar - -

A aba Monitor do app Strata ao lado de um agente de programação
-O Monitor do app Strata (à esquerda) enquanto um agente de programação escreve o jardim com pagode do vídeo (à direita)

- -- **No navegador:** abra `http://127.0.0.1:8080`. Lá tem o **Chat**, um **Monitor** ao vivo do modelo e da sua - GPU/CPU/RAM, e o **About** com as configurações e os endereços. -- **Seus apps e agentes de programação:** adicione um provedor "OpenAI-compatible" com a URL base - **`http://127.0.0.1:8080/v1`**. Qualquer chave de API e qualquer nome de modelo funcionam. - - Apps que usam a API da Anthropic: `http://127.0.0.1:8080/v1/messages` (Claude Code: - `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). - - Codex CLI e outros apps que usam a OpenAI Responses API: `/v1/responses` - ([configuração](docs/DETAILS.md#the-responses-api-and-codex-cli)). -- **Raciocínio:** escolha **off, low, medium ou high** no menu do chat ou no "reasoning effort" do seu app. Off é o - mais rápido. High é o melhor para perguntas difíceis. -- **Imagens:** responda sim para "Images?" na instalação. Depois clique em **Picture** no chat, ou anexe imagens no - seu app. Placas AMD entendem imagens no Linux usando o processador; no Windows, ainda não. -- **Do seu celular ou de outro PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `. Sempre defina uma chave. -- **Uma requisição por vez:** por padrão, o Strata responde uma requisição e as outras esperam. Para responder - várias ao mesmo tempo, defina `"parallel": 2` ([BATCHING.md](docs/BATCHING.md)). Numa placa de 12 GB, isso deixa - cada resposta mais lenta. -- **Prompts longos:** o Strata lê a primeira mensagem de uma conversa inteira, cerca de 1 minuto a cada 30,000 - tokens. As mensagens seguintes começam em segundos. - -Mais: [onde suas conversas ficam salvas](docs/INSTALL.md#where-things-are-stored), [a API](docs/DETAILS.md#using-it). - -### Opcional: mais velocidade com uma placa quando o modelo inteiro cabe na RAM - -Duas configurações opcionais (de RubenTorney, #1904 e #1905). Elas ajudam quando você usa uma placa de vídeo e sua RAM guarda todos os experts (o modo arena do Strata, por exemplo Q2_0 ou IQ3_XXS num PC com 64 GB). Abra sua configuração `strata-.json` na pasta de dados do Strata ([onde](docs/INSTALL.md#where-things-are-stored)) e adicione: - -- **Geração mais rápida:** `"--adapt-async", "1"` na lista `"args"`. O cache de experts passa a ser atualizado numa thread auxiliar em vez de pausar a resposta. Medido numa RTX 5070 (Windows, Q2_0): +4-5% de geração, +7-10% em código e documentos longos. As respostas podem diferir um pouco do padrão (ficam iguais de uma execução para outra). -- **Leitura do prompt mais rápida no Windows:** `"STRATA_PIN_BY_NEED": "1"` no bloco `"env"`. O Windows só consegue travar cerca de metade da RAM para a placa; isto trava primeiro os experts de que a placa realmente precisa. Medido na RTX 5070: +4,4% na leitura do prompt. - -```json -"args": [ ..., "--adapt-async", "1" ], -"env": { "STRATA_PIN_BY_NEED": "1" } +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex ``` -Reinicie o Strata (`START-HERE.bat` ou `./setup.sh`) depois da mudança. Para desfazer, remova as duas entradas. +No Windows, abra um novo terminal depois. Em seguida: + +```sh +strata launch +``` -## Algo deu errado? +Siga as instruções para baixar e iniciar um modelo. [Guia do Terminal](docs/TERMINAL_LAUNCH.md). -- **Meu PC travou na primeira vez que o Strata iniciou.** Isso é normal enquanto ele carrega o modelo. Espere e não - feche a janela. Ainda travado depois de 10 minutos? Reinicie o PC, feche outros programas e tente de novo, ou - escolha um tamanho menor. -- **Parou durante o download ou a instalação.** Rode `START-HERE.bat` (ou `./setup.sh`) de novo. Ele continua de - onde parou. -- **Está muito lento e a luz do disco não para de piscar, ou aparece "the engine stopped unexpectedly".** Seu PC - não tem RAM livre suficiente. Feche outros programas (navegadores usam muita), ou escolha um tamanho menor (Q2_0 - ou IQ2_XS). -- **Diz que a porta 8080 já está em uso.** O Strata já está rodando. Procure a janela dele. +
-Mais problemas e como resolver: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Ainda sem solução? Abra uma -[issue](https://github.com/Niko1221/Strata/issues) e anexe o `strata-.log` da pasta do Strata. Encontrou um -problema de segurança? Informe em particular: [SECURITY.md](SECURITY.md). +

+ Aplicativo de Terminal do Strata mostrando a atividade do modelo, a velocidade, a memória e as solicitações recentes +
Acompanhe seu modelo e seu hardware enquanto ele roda. +

-## Como funciona? + -Modelos como este normalmente rodam em servidores com centenas de gigabytes de memória de vídeo. Sua placa de vídeo -tem 12-24 GB. O Strata faz o modelo caber **dividindo o trabalho pelo PC inteiro**. Pense numa cozinha: o que você -usa o tempo todo fica na bancada, e o resto espera na despensa. +[Compilar a partir do código-fonte](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guia de instalação completo](docs/INSTALL.md) -

Os 24,576 experts do modelo: os mais usados na placa de vídeo, todos na RAM, uma tabela de consulta no SSD

+ -- **O modelo é uma equipe de 24,576 pequenos especialistas ("experts").** Cada palavra precisa de só 10 deles. -- **Sua placa de vídeo** guarda os poucos milhares de experts usados com mais frequência. **Sua RAM** guarda todos - eles, e **seu processador** trabalha no resto ao mesmo tempo. **Seu SSD** guarda uma grande tabela de consulta. +## Hardware -

Um pequeno ajudante adivinha as próximas palavras; o modelo grande confere todas de uma vez e fica com as certas

+| Hardware compatível | Guia | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Instalação para NVIDIA](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Instalação para AMD](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · experimental** | [Instalação para RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Instalação para Intel](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 ou mais novo** | [Instalação para Mac](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Instalação para Strix Halo](docs/STRIX_HALO.md) | -- **Adivinhar e conferir:** um pequeno ajudante adivinha as próximas palavras. O modelo grande confere todas de - uma vez. Você recebe a mesma resposta, 1.6-1.8x mais cedo. -- **Textos longos são lidos em grandes pedaços** (até 8,192 tokens por vez), a mais de 1,000 tokens por segundo. + -A explicação mais longa: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Cada parte e seus números: -[os detalhes](docs/DETAILS.md#how-it-works) e o [artigo](docs/paper/Strata-Paper.pdf). +## Ferramentas -## Créditos e licença +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, e outras, pelas APIs compatíveis com OpenAI e Anthropic. -O modelo é o [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next), da equipe Qwen. Ele foi -comprimido por [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) -e Unsloth. O Strata usa partes do [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). Todos os créditos: -[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). O Strata é de código aberto sob a [MIT License](LICENSE). -Algumas partes e todos os modelos têm licenças próprias ([quais](docs/HOW_IT_WORKS.md#license)). +Execute **`strata connect`** para ver as instruções da sua ferramenta. [Guia de conexão](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). + + + + + + +## Ajuda + +[Todos os guias](docs) · [Solução de problemas](docs/TROUBLESHOOTING.md) · [Relatar um bug](https://github.com/Niko1221/Strata/issues/new/choose) · +[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Como funciona](docs/HOW_IT_WORKS.md) · [Contribuir](CONTRIBUTING.md) ## Apoie o Strata -O Strata é gratuito e de código aberto. Se ele é útil para você, você pode apoiar o desenvolvimento: +**Ajude a manter a IA local aberta para todos.** Um café ajuda a financiar o desenvolvimento e os testes em mais hardware. + +Buy Me a Coffee: apoie o Strata + +[Licença MIT](LICENSE) · [Créditos e licenças dos modelos](docs/HOW_IT_WORKS.md#credits) · [Privacidade](docs/SAFETY.md) + + + +Para ferramentas de IA e leitores automáticos: referência técnica · instruções de instalação. -

Buy Me A Coffee

+**Patrocínios, parcerias de hardware ou colaborações:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/README.zh-CN.md b/README.zh-CN.md index 7ffb2e44fc5..2574b7b67ab 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,217 +1,188 @@ -

Strata

+

+ + + Strata + +

-[English](README.md) · **简体中文** · [日本語](README.ja.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · [Português](README.pt-BR.md) +

在你自己的电脑上运行强大的 AI。

+

本地聊天、写代码、处理图片。

-

在你自己的游戏电脑上运行 1250 亿参数的 AI 模型
-NVIDIA 或 AMD 显卡(12 GB 及以上)· Windows 或 Linux · 免费开源

+

+ 模型 · 安装 · + 硬件 · 工具 · + 帮助 · 支持 +

-

Strata 的模型写出的体素宝塔花园,在浏览器中运行
-体素宝塔花园,一次提示生成,在 RTX 5070 上用 Strata 运行(IQ3_S,128K 上下文)· -完整视频(49 秒)

+

+ 下载 Strata + MIT 许可证 + 在 Buy Me a Coffee 上支持 Strata +

-Strata 能在普通电脑上运行 **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)**。这是一个又大又聪明的 -AI 模型,通常要用服务器才能跑。它能聊天、写代码、看图片,还能配合你的应用和编程智能体一起工作。所有数据都留在你的电脑上。 +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

-## 速度有多快? +**免费、开源,由你自己运行。** 在桌面上使用 Strata,或搭配你喜欢的编程工具。无需账号。 -我们在两台普通的游戏电脑上做了测试。一个 token 大约相当于 ¾ 个英文单词。 +## 模型 -- **写回答:** 短对话中回复出现的速度。每秒 60 个 token 已经比你的阅读速度还快。 -- **读提示:** 读入你发送内容的速度(这里是一份 32K token 的文档、代码或聊天记录)。 +我们**首先推荐 ISTA-DASLab**,其次是 **Unsloth** 和其他提供方,前提是有内存放得下的兼容模型。 - - - -
NVIDIA:RTX 5070(12 GB)、Ryzen 5 7600、64 GB 内存AMD:RX 9070 XT(16 GB)、Ryzen 9 3900X、47 GB 内存
+
+  Qwen3.8-Flash-Next -| 规格 | 写回答 | 读提示 | -| --- | ---: | ---: | -| **Q2_0** | 94 tokens/s | 2,650 tokens/s | -| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | -| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | -| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | -| **Coder** | 55 tokens/s | 2,180 tokens/s | +| 提供方 | 可选项 | +| --- | --- | +| **ISTA-DASLab · 推荐** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S。[Coder:IQ1\_M](docs/MODELS.md#coder),适合写代码。 | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF)。占用内存更少,但速度更慢。 | +| **其他选项** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | -
+[比较大小、内存需求和兼容性](docs/MODELS.md)。 -| 规格 | 写回答 | 读提示 | -| --- | ---: | ---: | -| **Q2_0** | 60 tokens/s | 1,160 tokens/s | -| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | -| **Coder** | 44 tokens/s | 1,420 tokens/s | + -
+
+  Qwen3.6-35B-A3B -NVIDIA:Q2_0 用的是引擎 0.1.36,其他各行用的是 0.1.26(4K 回答,32K 提示)。完整表格见 -[DETAILS.md](docs/DETAILS.md#speed-measured)。显存越大的显卡越快:RTX 3090(24 GB)写回答应该能达到每秒约 -100-140 个 token。长对话和其他显卡的数据:[各模型的速度](docs/MODELS.md#how-fast-is-each-size)、 -[社区测试结果](docs/COMMUNITY_BENCHMARKS.md)。 +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0。这些是目前文档中收录的该模型的版本。 -

请我喝杯咖啡
-Strata 是免费的。如果它在你的电脑上跑得不错,请我喝杯咖啡,让这个项目继续下去。

+[模型指南和兼容性](docs/QWEN36.md)。 -## 你需要什么 - -| | | -| --- | --- | -| **显卡** | **NVIDIA** GeForce RTX 20、30、40 或 50 系列,或 **AMD** Radeon RX 7900 XT / XTX、RX 7800 XT / 7700 XT、RX 9060 XT、RX 9070 / 9070 XT、Radeon AI PRO R9700 或 RX 6800 / 6900 系列。需要 **12 GB 或以上显存**。 | -| **内存** | 32 GB 或以上。内存大小决定能装下[哪个模型](#该选哪个模型)。64 GB 可以运行所有规格。 | -| **硬盘** | 约 80 GB 可用空间。尽量用 SSD:第一次启动会快很多。 | -| **系统** | Windows 10 / 11 或 Linux,以及 NVIDIA 或 AMD 的最新显卡驱动。 | +
-其他的都由安装程序搞定。两到三张显卡可以分担同一个模型([多 GPU](docs/MULTI_GPU.md))。 +
+  DeepSeekV4.1-Flash-1017 -实验性支持,由社区成员在自己的机器上编写和测试: +可在**桌面应用**和**终端**中使用。内存放不下的部分会从 SSD 读取,所以需要大量空闲磁盘空间。 -- **较老的显卡**(Tesla P40 / V100、GTX 10、Radeon VII / MI50、RX 6700 XT、RX 5500 XT):[较老的 GPU](docs/OLDER_GPUS.md)。 -- **Intel Arc**,在 Linux 上从源码构建:[Intel Arc](docs/INTEL_ARC.md)。 -- **AMD Ryzen AI Max(Strix Halo)**,在 Linux 上从源码构建:[Strix Halo](docs/STRIX_HALO.md)。 -- **不支持 AVX2 的老处理器**:能用,但很慢。[较老的 CPU](docs/INSTALL.md#older-cpus-experimental)。 +| 版本(ISTA-DAS) | 下载大小 | 所需空闲磁盘 | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | 约245 GB | +| 2.00 bpw | 257 GB | 约265 GB | +| 2.25 bpw | 274 GB | 约280 GB | -完整列表:[docs/INSTALL.md](docs/INSTALL.md#what-you-need)。 +支持 NVIDIA RTX 30、40 和 50 系列(Windows 和 Linux),以及 AMD Radeon AI PRO R9700(Linux)。安装程序会下载模型文件和 DeepSeek 引擎,然后启动模型。 -## 安装 +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` -### 让你的 AI 帮你装 +以下为 Strata 0.2.5 上 2.00 bpw 版本的实测结果。“输出”是回答的速度,“提示词”是 Strata 读取你输入内容的速度。 -你在用 AI 编程助手吗(Claude Code、Cursor、Codex、GitHub Copilot 等)?把下面这段粘贴给它: +| 硬件 | 输出 | 提示词 | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB 内存 | 4 到 6 tokens/s | 约 110 tokens/s(4K) | +| RTX 3060 12 GB, 46 GB 内存 | 9 到 11 tokens/s | 约 155 tokens/s(4K) | +| 1x Radeon AI PRO R9700, 251 GB 内存 | 21 到 25 tokens/s | 320 到 360 tokens/s (8K) | +| 4x Radeon AI PRO R9700 | 74 到 77 tokens/s | 400 到 450 tokens/s (8K) | -```text -Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. -``` +[内存、磁盘和详细信息](docs/DEEPSEEK41.md) · [发行说明](https://github.com/Niko1221/Strata/releases) -它会检查你的显卡、内存和硬盘,选出合适的模型。然后安装并启动它,再告诉你怎么连接你的应用。AI 工具也可以通过 -Strata 的 [MCP 服务器](docs/MCP_SERVER.md)来安装、启动和停止 Strata。 +
-### 或者自己动手 + -[下载 Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) 并解压(或者用 `git clone`)。 -**Windows:** 双击 **`START-HERE.bat`**。**Linux:** 在 Strata 文件夹里运行 **`./setup.sh`**。 +不确定哪个放得下?[为你的电脑选择模型](docs/MODELS.md#pick-by-memory)。 -**Mac(Apple 芯片,M1 到 M5,macOS 15 或更新版本):** 先安装一次 Apple 的 Command Line Tools(在终端里运行 `xcode-select --install`;不需要 Xcode 本身)。然后在 Strata 文件夹里打开终端,运行 **`./setup.sh`**。它会在你的 Mac 上编译 Mac 版引擎(大约 7 分钟),问同样的问题,下载模型并启动。下次运行 `./setup.sh` 会马上启动。哪个大小适合你的 Mac、速度如何:[docs/MAC.md](docs/MAC.md)。 +## 安装 -NVIDIA 和 AMD 的步骤完全一样。安装程序会识别你的显卡,并装好对应的引擎。它会问你几个问题: + -- 用哪个模型、哪个规格, -- 上下文多大(模型能记住多少文字), -- 是否要识别图片。 +### 桌面应用 -每次直接按回车就是推荐选项。之后它会下载模型(约 70 GB)并启动。如果下载中断了,再运行一次即可:它会从中断的地方继续。 -浏览器会打开 Strata 应用,地址是 `http://127.0.0.1:8080`。 +**[下载适用于 Windows、Linux 或 Mac 的 Strata →](https://github.com/Niko1221/Strata/releases/latest)** -> **模型启动时,你的电脑可能会变慢或卡住 1-3 分钟**(第一次最久)。 -> Strata 会把 35-55 GB 加载到内存,并为显卡锁定其中一部分。这是正常的。请耐心等待,不要关闭窗口。 -> 窗口里会显示 Strata 正在做什么。 +安装应用,选择模型,就可以开始聊天。每个系统只有一个安装程序。首次启动时,应用会下载适合你显卡的引擎。[安装程序帮助](docs/INSTALL.md#the-app)。 -**下次使用时**,再运行一次 `START-HERE.bat`(或 `./setup.sh`)。它会马上启动,已下载的东西不会重复下载。关闭它的窗口就能停止模型。 -`UPDATE.bat`(`./update.sh`)只更新 Strata,不启动。更新、Docker、多张显卡、文件存放位置以及所有选项: -[docs/INSTALL.md](docs/INSTALL.md)。 +文件: `Strata-0.2.9-windows-x64-setup.exe` · `Strata-0.2.9-linux-x86_64.AppImage` · `Strata-0.2.9-macos-arm64.dmg` -## 该选哪个模型 +

+ Strata 桌面应用,聊天和实时代码预览并排显示 +
聊天、文件和实时预览都在一个窗口里。 +

-安装程序会根据你的内存推荐一个。同一个模型有几种规格,压缩程度不同。规格越小越快,越大越聪明一些。 + -| 你的内存 | 选择 | 原因 | -| --- | --- | --- | -| **32 GB** | **Coder** | 32 GB 装得下,而且专为代码打造(如果显卡是 24 GB,Q2_0 和 IQ2_XS 也能跑) | -| **48 GB** | **IQ2_XS**(或 Q2_0,最快) | 更大的规格装不下 | -| **64 GB** | **IQ2_XS**(推荐),或 IQ3_XXS / IQ3_S | 所有规格都装得下;IQ3_S 最好,也最慢 | -| **96 GB 或以上** | **IQ3_S**,或 Unsloth 的 UD-IQ4_XS(约 4-bit) | 开着其他程序也能放下最大的规格 | +### 终端应用 -- **[Coder](docs/MODELS.md#coder):** 编程版本,去掉了一半专家。它达到完整模型 SWE-bench Verified 分数的 91%(由其作者测得), - 32 GB 内存就能装下。代码以外的能力较弱,包括中文和其他中日韩文本(#438)。这类用途请选 Q2_0、IQ2_XS 或 IQ3_S, - 它们保留了所有专家。 -- **[Swift 1.5](docs/MODELS.md#swift-15):** 一个微调版本,回答前思考的时间短得多。你能更早拿到答案,质量基本不变。 -- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** Unsloth 的约 4-bit 版本,质量介于 IQ3_S 和 UD-Q4_K_XL 之间。 - 下载 94 GB。内存少于约 80 GB 时,Strata 回答时要从 SSD 读取其中一部分,所以会更慢(NVMe SSD 有帮助)。 -- **[Unsloth UD-Q4_K_XL、UD-Q5_K_XL、UD-Q6_K_XL 和 Q8_0](docs/MODELS.md#unsloths-files-ud-iq4_xs-to-q8_0):** 4 到 8 位,更接近完整模型(下一个 token - 与 Q8_0 相同的比例为 93-95%)。所有专家都能放进内存时速度很快(UD-Q4_K_XL 约需 88 GB,Q8_0 约需 136 GB);内存不够时, - Strata 回答时要从 SSD 读取一部分,会慢很多(64 GB 的电脑上 UD-Q4_K_XL 每秒 7-8.5 个 token)。 -- **[OrcaRouter 的 Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** 需要手动设置,不在安装程序的菜单里。 +更喜欢终端?安装 Strata,然后运行 **`strata launch`**。 -规格、下载以及各配置能装下什么:[docs/MODELS.md](docs/MODELS.md)。以后想再添加模型,运行 -`SETUP.bat`(Linux:`./setup.sh --setup`)。 +
+安装命令 -## 使用方法 +**Linux / Mac** -

Strata 应用的 Monitor 标签页,旁边是一个编程智能体
-Strata 应用的 Monitor(左),编程智能体正在写视频里的宝塔花园(右)

+```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +``` -- **在浏览器里:** 打开 `http://127.0.0.1:8080`。里面有 **Chat**(聊天)、实时 **Monitor**(监控模型和你的 - GPU/CPU/内存),以及 **About**(设置和地址)。 -- **你的应用和编程智能体:** 添加一个“OpenAI 兼容”的提供商,base URL 填 **`http://127.0.0.1:8080/v1`**。 - API key 和模型名随便填都行。 - - 使用 Anthropic API 的应用:`http://127.0.0.1:8080/v1/messages`(Claude Code: - `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`)。 - - Codex CLI 和其他使用 OpenAI Responses API 的应用:`/v1/responses` - ([设置方法](docs/DETAILS.md#the-responses-api-and-codex-cli))。 -- **思考:** 在聊天菜单或应用的“reasoning effort”里选择 **off、low、medium 或 high**。off 最快, - high 最适合难题。 -- **图片:** 在安装时对“Images?”选是。然后在聊天里点 **Picture**,或在你的应用里附上图片。 - AMD 显卡在 Linux 上通过处理器识别图片;在 Windows 上暂时还不行。 -- **从手机或另一台电脑访问:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `。一定要设置 key。 -- **一次处理一个请求:** 默认情况下 Strata 一次只回答一个请求,其他请求排队等待。想同时回答多个, - 设置 `"parallel": 2`([BATCHING.md](docs/BATCHING.md))。在 12 GB 显卡上,这会让每个回答变慢。 -- **长提示:** Strata 会完整读入对话的第一条消息,大约每 30,000 个 token 需要 1 分钟。之后的消息几秒内就开始回答。 +**Windows PowerShell** -更多:[聊天记录存在哪里](docs/INSTALL.md#where-things-are-stored)、[API](docs/DETAILS.md#using-it)。 +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` -### 可选:整个模型都能放进内存时,单卡再提速 +在 Windows 上,安装后请打开一个新的终端。然后运行: -两个可选设置(来自 RubenTorney 的 #1904 和 #1905)。适用于只用一张显卡、并且内存能放下所有专家的情况(Strata 的 arena 模式,例如 64 GB 电脑上的 Q2_0 或 IQ3_XXS)。打开 Strata 数据文件夹里的配置文件 `strata-.json`([在哪里](docs/INSTALL.md#where-things-are-stored)),加入: +```sh +strata launch +``` -- **生成更快:** 在 `"args"` 列表里加 `"--adapt-async", "1"`。专家缓存改在辅助线程里更新,不再暂停回答。在 RTX 5070(Windows,Q2_0)上实测:生成 +4-5%,代码和长文档 +7-10%。回答可能与默认设置略有不同(但每次运行都一样)。 -- **Windows 上读取提示更快:** 在 `"env"` 块里加 `"STRATA_PIN_BY_NEED": "1"`。Windows 只能为显卡锁定大约一半的内存;这个设置会先锁定显卡真正需要的专家。在 RTX 5070 上实测:读取提示 +4.4%。 +按提示下载并启动模型。[终端指南](docs/TERMINAL_LAUNCH.md)。 -```json -"args": [ ..., "--adapt-async", "1" ], -"env": { "STRATA_PIN_BY_NEED": "1" } -``` +
-修改后重启 Strata(`START-HERE.bat` 或 `./setup.sh`)。要撤销,删掉这两项即可。 +

+ Strata 终端应用,显示模型活动、速度、内存和最近的请求 +
模型运行时,随时查看模型和硬件状态。 +

-## 出问题了? + -- **Strata 第一次启动时电脑卡死了。** 加载模型时这是正常的。请耐心等待,不要关闭窗口。 - 10 分钟后还卡着?重启电脑,关掉其他程序再试一次,或者换一个更小的规格。 -- **下载或安装时中断了。** 再运行一次 `START-HERE.bat`(或 `./setup.sh`)。它会从中断的地方继续。 -- **非常慢,硬盘灯一直闪,或者提示“the engine stopped unexpectedly”。** 你的电脑可用内存不够。 - 关掉其他程序(浏览器很占内存),或者换一个更小的规格(Q2_0 或 IQ2_XS)。 -- **提示 8080 端口已被占用。** Strata 已经在运行了。找一下它的窗口。 +[从源码构建](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [完整安装指南](docs/INSTALL.md) -更多问题和解决办法:[docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)。还是解决不了?提交一个 -[issue](https://github.com/Niko1221/Strata/issues),并附上 Strata 文件夹里的 `strata-.log`。发现了安全问题? -请私下报告:[SECURITY.md](SECURITY.md)。 + -## 它是怎么工作的? +## 硬件 -这类模型通常运行在拥有数百 GB 显存的服务器上。而你的显卡只有 12-24 GB。Strata 让模型装得下的办法是 -**把工作分摊到整台电脑上**。可以想象一个厨房:常用的东西放在台面上,其余的放在储藏室里。 +| 支持的硬件 | 指南 | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 系列** | [NVIDIA 安装](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900、RX 9060 / 9070、AI PRO R9700** | [AMD 安装](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · 实验性** | [RX 6000 安装](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Intel 安装](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 或更新** | [Mac 安装](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo 安装](docs/STRIX_HALO.md) | -

模型的 24,576 个专家:最常用的在显卡上,全部在内存里,一张查找表在 SSD 上

+ -- **这个模型是由 24,576 个小专家(“experts”)组成的团队。** 每个词只需要其中 10 个。 -- **你的显卡** 存放最常用的几千个专家。**你的内存** 存放全部专家, - **你的处理器** 同时处理其余的部分。**你的 SSD** 存放一张大查找表。 +## 工具 -

一个小助手猜测接下来的几个词;大模型一次性全部检查,保留正确的

+**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**,也可以通过兼容 OpenAI 和 Anthropic 的 API 使用更多工具。 -- **先猜,再检查:** 一个小助手先猜接下来的几个词,大模型再一次性检查它们。答案完全一样,但快 1.6-1.8 倍。 -- **长文本分大块读入**(每次最多 8,192 个 token),速度超过每秒 1,000 个 token。 +运行 **`strata connect`**,查看你所用工具的设置方法。[连接指南](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect)。 -更详细的解释:[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md)。每个部分及其数据: -[详细说明](docs/DETAILS.md#how-it-works)和[论文](docs/paper/Strata-Paper.pdf)。 + + + + -## 致谢与许可证 +## 帮助 -模型是 Qwen 团队的 [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)。它由 -[ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF)、UkisAI(Swift 1.5) -和 Unsloth 压缩。Strata 使用了 [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) 的部分代码。完整致谢: -[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits)。Strata 以 [MIT 许可证](LICENSE)开源。少数部分和每个模型 -有各自的许可证([具体是哪些](docs/HOW_IT_WORKS.md#license))。 +[全部指南](docs) · [故障排查](docs/TROUBLESHOOTING.md) · [报告问题](https://github.com/Niko1221/Strata/issues/new/choose) · +[基准测试](docs/COMMUNITY_BENCHMARKS.md) · [工作原理](docs/HOW_IT_WORKS.md) · [参与贡献](CONTRIBUTING.md) ## 支持 Strata -Strata 免费且开源。如果它对你有用,欢迎支持它的开发: +**帮助本地 AI 保持开放。** 一杯咖啡能帮助我们在更多硬件上开发和测试。 + +Buy Me a Coffee:支持 Strata + +[MIT 许可证](LICENSE) · [致谢和模型许可证](docs/HOW_IT_WORKS.md#credits) · [隐私](docs/SAFETY.md) + + + +面向 AI 工具和自动阅读器: 技术参考 · 安装说明 -

请我喝杯咖啡

+**赞助、硬件合作或其他合作:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/SECURITY.md b/SECURITY.md index 476dab9751d..8afbf44cfec 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -23,8 +23,9 @@ this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAIL - **Where it listens.** `127.0.0.1` by default. `--host 0.0.0.0` (or `"host"` in `strata-.json`) opens it to your network, and the server then warns when no API key is set. - **API key.** `"api_key"` in the run config (or `STRATA_API_KEY`) is required on `/v1/*` and on every endpoint - that shows the model's state, requests or answers (`/status`, `/metrics`, `/settings`, `/mcp`, `/props`, `/slots`, - `/api/requests`, `/config`) and on every `POST`. It is compared in constant time. Set one before you open the + that shows the model's state, requests or answers (`/status`, `/metrics`, `/metrics/prometheus`, `/settings`, + `/mcp`, `/props`, `/slots`, `/api/requests`, `/config`) and on every `POST`. It is compared in constant time. + Set one before you open the server to your network or put a tunnel in front of it. - **Host check (DNS rebinding, 0.1.38).** Without an API key the server answers only requests whose `Host` is a name it knows (`localhost`, an IP address, the address it listens on and, when it listens beyond this PC, this PC's @@ -43,4 +44,53 @@ this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAIL last few prompts, whatever `"api_monitor"` says, to encode the next turn faster; no endpoint shows them, and they are gone when the server stops. +## The desktop app and the Terminal + +Strata comes in three parts that share one engine: the **desktop app**, the **Terminal** (`strata`) and the **engine** that runs +the model. The section above is about the engine's HTTP server. This is what the other two add. + +- **The app's host listens on this PC only.** The app serves its page from a local host process on `127.0.0.1` (port 8791 unless + changed). A request to its `/api/` endpoints that carries a browser `Origin` from any other site gets 403. The app shell holds a + random secret (32 characters or more, compared in constant time) that is needed to quit the host or tell it which window is open, + and the host gives its own helper processes a second random secret. By default the models the app starts are served on this PC only. +- **Sharing is a separate, key-protected listener.** "Share with other devices" (and the Cloudflare tunnel) will not start until an + API key is set. It opens a different listener that answers only `/v1/models`, `/v1/chat/completions` and `/v1/messages`, never the + app's page or its host endpoints. +- **App and Terminal talk through an owner channel.** One owner process per installation starts and ends the engine, and a second + client (the Terminal) attaches to it. On macOS and Linux that is a private Unix socket in a folder only you can open. On Windows it + is a TCP listener on `127.0.0.1` that answers only requests carrying a 256-bit token kept in an owner-only folder. That is a weaker + guarantee than a socket other users cannot open: on Windows the token is what protects it, as with any loopback service that has a + token (`strata_control/owner_transport.py`). The bridge between the app shell and the host (used for the app update) is also loopback and protected by a token. +- **Starting a model and serving never download anything.** Downloads and updates are one explicit step: `strata update`, or "Update + engine" and "Update Strata" in the app's Settings. Models and saved tuning are never replaced by an update. +- **Updates come from a signed feed.** The release publishes `strata-feed.json` and `strata-feed.json.sig` (Ed25519). An installed + Strata checks the signature against the public key it carries (`strata_control/update_keys.json`), refuses a feed older than the last + one it accepted (a replayed old feed) or expired, and checks every engine package against its SHA-256, its signed manifest and the + card in your PC before it test-starts it and switches to it. Any failure keeps the engine you had. The app installer itself is signed + with a separate key (Tauri's minisign key) that the app and the Terminal both check. The private keys are kept offline by the owner. + See [packaging/UPDATES.md](packaging/UPDATES.md). + +### How far to trust `curl | sh` and `irm | iex` + +The Terminal installs with one line: + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +Piping a script into a shell runs whatever the server sends, so it deserves the same care as running any downloaded program. +What the script does is short and written at its top: it fetches the Terminal archive named in the release's `install-manifest.txt`, +checks its SHA-256, unpacks it into your home folder (no administrator rights, nothing outside your home), checks the release's signed feed +with the Terminal it just unpacked and removes it again if that fails, and puts `strata` on your PATH. + +Those checks have a limit. The checksum comes from the same release as the archive, and the public key that checks the feed arrives inside +that archive, so for the first install all trust rests on HTTPS and on the `Niko1221/Strata` GitHub release itself. The checks catch a +damaged or half-finished download and a feed that was not signed by the release key; they do not protect you if the release has been replaced +by someone who controls it. Later updates are checked against the key already on your PC, which is a stronger position. + +If that is not enough: save the script (`curl -fsSLO https://github.com/Niko1221/Strata/releases/latest/download/install.sh`), read it, and +run it from the file; or install the desktop app or build from source instead and check the code you build. + Strata has not had an outside security audit yet. +What Strata downloads, when it uses the internet, what stays on your PC and how downloads are checked is written up in [docs/SAFETY.md](docs/SAFETY.md). diff --git a/START-HERE.bat b/START-HERE.bat index dfb92feb847..5f255c07446 100644 --- a/START-HERE.bat +++ b/START-HERE.bat @@ -2,8 +2,13 @@ rem Strata for Windows: the first run installs everything and starts the model; later runs just start it. rem Needs only an NVIDIA or AMD graphics driver. Python is installed for your user account if it is missing (no admin needed). setlocal +rem Python reads and writes text as UTF-8, not in the Windows code page (cp1251, cp866, ...): a folder or user name with Cyrillic or other letters stays intact (#3202). +set "PYTHONUTF8=1" title Strata cd /d "%~dp0" +rem A bundled Python runtime (the python\ folder of the terminal archive) is used when it is there: nothing to find, +rem install or download. SETUP.bat and UPDATE.bat run this file, so they use it too. +if exist "python\python.exe" goto bundled if exist ".venv\Scripts\python.exe" goto run call :findpy @@ -36,6 +41,14 @@ echo Could not create the Python environment in .venv pause exit /b 1 +:bundled +set "PYTHONNOUSERSITE=1" +set "PYTHONHOME=" +set "PYTHONPATH=" +"python\python.exe" setup.py %* +if errorlevel 1 pause +exit /b + :run ".venv\Scripts\python.exe" setup.py %* if errorlevel 1 pause diff --git a/UPDATE.bat b/UPDATE.bat index 198e1a997c6..c0fd78a14dc 100644 --- a/UPDATE.bat +++ b/UPDATE.bat @@ -2,7 +2,8 @@ rem Update Strata without starting the model (#475): the newest code (git pull, when this folder is a git clone), then rem what START-HERE.bat does before a start - the engine (a new one when this version needs it), the Python packages, rem each installed model's settings and draft subset. The model files are not touched. Start the model later with -rem START-HERE.bat. Options are passed on to setup.py. +rem START-HERE.bat. Options are passed on to setup.py. The bundled Python (python\ beside this file) is used when +rem there is one: START-HERE.bat, which this file runs, picks it. setlocal title Strata - update cd /d "%~dp0" diff --git a/apps/desktop/package-lock.json b/apps/desktop/package-lock.json new file mode 100644 index 00000000000..448060e1ca1 --- /dev/null +++ b/apps/desktop/package-lock.json @@ -0,0 +1,232 @@ +{ + "name": "strata-desktop", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "strata-desktop", + "version": "0.1.0", + "devDependencies": { + "@tauri-apps/cli": "2.12.3" + } + }, + "node_modules/@tauri-apps/cli": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.3.tgz", + "integrity": "sha512-f7/LsY74SVb1ChmOPw1ajOpxii0GSzDAgmWHRci8JUYuuai04rXsSbFobpmB0sP2DdlvMD/B5ZotEn8GOGMRUg==", + "dev": true, + "license": "Apache-2.0 OR MIT", + "bin": { + "tauri": "tauri.js" + }, + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/tauri" + }, + "optionalDependencies": { + "@tauri-apps/cli-darwin-arm64": "2.12.3", + "@tauri-apps/cli-darwin-x64": "2.12.3", + "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.3", + "@tauri-apps/cli-linux-arm64-gnu": "2.12.3", + "@tauri-apps/cli-linux-arm64-musl": "2.12.3", + "@tauri-apps/cli-linux-riscv64-gnu": "2.12.3", + "@tauri-apps/cli-linux-x64-gnu": "2.12.3", + "@tauri-apps/cli-linux-x64-musl": "2.12.3", + "@tauri-apps/cli-win32-arm64-msvc": "2.12.3", + "@tauri-apps/cli-win32-ia32-msvc": "2.12.3", + "@tauri-apps/cli-win32-x64-msvc": "2.12.3" + } + }, + "node_modules/@tauri-apps/cli-darwin-arm64": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.3.tgz", + "integrity": "sha512-xmVNoJOOKzKLj7GLHXmXLimRby9M42aBIJa0sB80N7o24eKV5JiVmToKTRLVH9yhL05GZ/B6rSSOmbzNFJwBAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-darwin-x64": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.3.tgz", + "integrity": "sha512-URd+0usfmUQQyb5kNPiKt2OT8gp7oGU7QR+qOppB6e35mpVBFFVNhWc9oWb3p0u71fDJ09DpF4T6m9xYxoIB8g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.3.tgz", + "integrity": "sha512-0kwUVx2LbmOoTRlwF1oDww7th4/NSluv4ZBQ6KRZsFKg4g0TlTcIiJ0VehqkQYUeC9xIT1Mk6XtF52mI155VSQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-gnu": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.3.tgz", + "integrity": "sha512-gKSGDx6fx+HBLQmG6guChFdisbrCSdx9Yli+j5teOa64gm1CeM+C6NLru5Pj3ZkkEep05BmCFjxvX+cjqAycZQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-musl": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.3.tgz", + "integrity": "sha512-Yr59qMy/gcvAfBuFdCGlAmGiLsYWMFDbsP4bAI6iNBzcJTGrYWZGeiQhGDo29MQwfF/NUBqyM2qljXu5tZ6wjQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-riscv64-gnu": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.3.tgz", + "integrity": "sha512-jKr0/REBMnLKC0OwPQZkyge0mKDaNZ0b/AbfGwVyCgFfwS730EVLfVDo3nt7MUu6jJaytRq08+xSj5qfy+U1+Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-gnu": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.3.tgz", + "integrity": "sha512-gTkEqJAGCMROGanxHnzaJzQ+/rXl39HWVg0/hDODS1wDWBGqoceqGC6Qm1+mQbyT11xnsB8mKu/gyVID/YpFIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-musl": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.3.tgz", + "integrity": "sha512-T2dTxL1svRym71fZtaW4pZYXbthbfFsEJr1NeOUg/p7laWXZbUt/8DMSZf8recu9f7+1F/Lv00HtzsEu6vDO9w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-arm64-msvc": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.3.tgz", + "integrity": "sha512-eoiQwpEZWbpsVHcM9BAzqqe4TCHszvr3rsM7pUQ4ofLK0lF1i1d/jX0Qo5DYMqcrUtwQuDdDuOCbcT0Izf1VwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-ia32-msvc": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.3.tgz", + "integrity": "sha512-kE+KUg6Dbbkgvcw0m99wJVIToFQzJqpMBAXah74WqxaLzssNwSTUccrHp6+QVzMhjQP330tvekFmnQF+0NbE6Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-x64-msvc": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.3.tgz", + "integrity": "sha512-L7wndWAgX2mLW7alswpL3d1R0P9FN2WYBgHaQkAYEBxHHGkY4vFX9CjcRQ1LAxDAMIJxrY7/aDziFJeChS84NQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + } + } +} diff --git a/apps/desktop/package.json b/apps/desktop/package.json new file mode 100644 index 00000000000..3fa03c9f6e4 --- /dev/null +++ b/apps/desktop/package.json @@ -0,0 +1,20 @@ +{ + "name": "strata-desktop", + "productName": "Strata", + "version": "0.2.10", + "private": true, + "description": "Strata Desktop - local AI, tuned to one model.", + "scripts": { + "build:ui": "npm --prefix ../host run build", + "typecheck:ui": "npm --prefix ../host run typecheck", + "test:ui": "npm --prefix ../host test", + "tauri": "tauri", + "dev": "npm run build:ui && tauri dev", + "build": "npm run build:ui && tauri build", + "build:app": "npm run build:ui && tauri build --bundles app", + "dmg": "npm run build:ui && tauri build --bundles dmg" + }, + "devDependencies": { + "@tauri-apps/cli": "2.12.3" + } +} diff --git a/apps/desktop/scripts/app-close-matrix.py b/apps/desktop/scripts/app-close-matrix.py new file mode 100644 index 00000000000..31e65b98961 --- /dev/null +++ b/apps/desktop/scripts/app-close-matrix.py @@ -0,0 +1,361 @@ +#!/usr/bin/env python3 +"""The installed Windows app, closed every way, with a stub engine: nothing may be left running. + + python apps/desktop/scripts/app-close-matrix.py --install [--scenarios all] [--report out.json] + +For each case it starts the REAL installed `strata-desktop.exe` (its window opens), loads a stub engine through the host's API +(profile + `runtime start` under Control's owner runtime, exactly the app's path), records every process of the tree (the app, +the host, Control, the owner host, the server, the engine), ends the app one way, and asserts: + * no process of the tree is left, the engine's port is free, the runtime lease can be taken again; + * the engine got the clean stop where the way of closing allows one (normal close, window X); + * the next load of the same slot works (a lost owner's state is cleaned, not a blocker). +It also proves a second launch focuses the open window and starts nothing, and that one app runs two engines and closes both. +Everything per-user lives under a scratch folder; the stub engine is a script. No real engine ever runs. +""" +from __future__ import annotations + +import argparse +import ctypes +import json +import os +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request +from ctypes import wintypes +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT)) + +import psutil # noqa: E402 + +from strata_control import procs, runtime # noqa: E402 +from tests.terminal.lifecycle_matrix import install_fake_engine, port_open # noqa: E402 + +if os.name != "nt": + raise SystemExit("this matrix drives the Windows installer's app") + +user32 = ctypes.WinDLL("user32", use_last_error=True) +WM_CLOSE = 0x0010 + + +def main_window(pid: int) -> int | None: + found = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def visit(hwnd, _): + owner = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + if owner.value == pid and user32.IsWindowVisible(hwnd): + buf = ctypes.create_unicode_buffer(256) + user32.GetWindowTextW(hwnd, buf, 256) + if buf.value.strip() == "Strata": + found.append(hwnd) + return True + user32.EnumWindows(visit, 0) + return found[0] if found else None + + +class Scratch: + def __init__(self, root: Path, install: Path): + self.root, self.install = root, install + self.components = root / "components" + self.models = root / "models" + self.mark = root / "mark" + for d in (self.components, self.models, self.mark, root / "local", root / "home", root / "appdata", root / "webview"): + d.mkdir(parents=True, exist_ok=True) + install_fake_engine(self.components) + from tools.strata_tokenizer import BYTE_TO_UNICODE + tok = self.models / "tokenizer" + tok.mkdir() + tokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ["ab", "<|im_start|>", "<|im_end|>", "<|endoftext|>"] + (tok / "vocab.json").write_text(json.dumps({t: i for i, t in enumerate(tokens)})) + (tok / "merges.txt").write_text("a b") + (tok / "token_type.json").write_text(json.dumps([0] * 257 + [3, 3, 3])) + for name in ("stub", "stub2"): + (self.models / f"strata-{name}.json").write_text(json.dumps({ + "exe": "component:strata-engine", "backend": "cuda", "tokenizer": str(tok), "args": [], "cwd": str(root), + "model_name": name, "host": "127.0.0.1", "port": 0})) + self.env = {**os.environ, "STRATA_COMPONENTS_DIR": str(self.components), "STRATA_PROFILE_DIR": str(root / "profiles"), + "STRATA_RUNTIME_DIR": str(root / "runtime"), "STRATA_INSTALL_DIR": str(self.models), + "STRATA_MODELS_DIR": str(root / "models-unused"), "STRATA_ENGINE_BACKEND": "cuda", + "STRATA_HOME": str(root / "home"), "APPDATA": str(root / "appdata"), "LOCALAPPDATA": str(root / "local"), + "WEBVIEW2_USER_DATA_FOLDER": str(root / "webview"), "FAKE_ENGINE_MARK": str(self.mark), + "FAKE_ENGINE_SLOW_STEPS": "0", "PYTHONDONTWRITEBYTECODE": "1"} + self.env.pop("STRATA_API_KEY", None) + for key in ("STRATA_COMPONENTS_DIR", "STRATA_PROFILE_DIR", "STRATA_RUNTIME_DIR", "LOCALAPPDATA", "STRATA_ENGINE_BACKEND", + "STRATA_NO_ACQUIRE", "FAKE_ENGINE_MARK"): + os.environ[key] = self.env.get(key, "1") # this process reads the same runtime and records folders + + +class App: + def __init__(self, scratch: Scratch): + self.s = scratch + self.proc = subprocess.Popen([str(scratch.install / "strata-desktop.exe")], cwd=scratch.install, env=scratch.env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.base = None + + def host(self): + for child in psutil.Process(self.proc.pid).children(recursive=True): + if child.name().lower() == "node.exe": + return child + return None + + def wait_up(self, seconds=90): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if self.proc.poll() is not None: + raise RuntimeError(f"the app exited with {self.proc.returncode}") + try: + host = self.host() + if host: + for c in host.net_connections(kind="tcp"): + if c.status == "LISTEN" and c.laddr.ip == "127.0.0.1": + base = f"http://127.0.0.1:{c.laddr.port}" + try: + if urllib.request.urlopen(base + "/api/health", timeout=2).status == 200 and main_window(self.proc.pid): + self.base = base + return + except OSError: + pass + except psutil.Error: + pass + time.sleep(0.5) + raise RuntimeError("the app did not come up") + + def call(self, path, method="GET", body=None): + req = urllib.request.Request(self.base + path, method=method, data=None if body is None else json.dumps(body).encode(), + headers={"content-type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=120) as r: + return json.loads(r.read() or b"null") + except urllib.error.HTTPError as exc: + raise RuntimeError(f"{method} {path} -> {exc.code} {exc.read()[:300]!r}") from None + + def load(self, model, multiple=False): + self.call("/api/native?refresh=1") + started = self.call("/api/native/operations", "POST", {"kind": "load", "args": {"model": model, **({"multiple": True} if multiple else {})}}) + deadline = time.monotonic() + 180 + while time.monotonic() < deadline: + state = self.call("/api/native") + job = next((j for j in state["jobs"] if j["id"] == started["id"]), None) + if job and job["state"] != "running": + if job["state"] != "done": + raise RuntimeError(f"load {model}: {job['state']} {job.get('error')}") + return state + time.sleep(0.3) + raise RuntimeError("load did not finish") + + +def tree_of(app: App, slots=("app-1",)) -> tuple[list[procs.Ident], list[int]]: + idents, ports = [], [] + members = [psutil.Process(app.proc.pid), *psutil.Process(app.proc.pid).children(recursive=True)] + pids = {p.pid for p in members} + for slot in slots: + state = runtime._read_state(slot) + if state: + pids.add(state["host_pid"]) + for r in procs.records(): + if r.get("profile") in slots: # the app's own slots; a Terminal service is not part of the app's tree + pids.add(r["pid"]) + for pid in pids: + token = procs.start_token(pid) + if token: + idents.append(procs.Ident(pid, token, tuple(procs.command_line(pid) or []))) + return idents, ports + + +def survivors(idents): + return [f"{i.pid} {' '.join(i.cmd)[:80]}" for i in idents if procs.start_token(i.pid) == i.token] + + +def wait_gone(idents, seconds): + deadline = time.monotonic() + seconds + left = survivors(idents) + while left and time.monotonic() < deadline: + time.sleep(0.25) + left = survivors(idents) + return left + + +def lease_free() -> bool: + try: + fd = runtime.acquire_activity_lease(shared=False) + except Exception: # noqa: BLE001 + return False + runtime._unlock_file(fd) + os.close(fd) + return True + + +def control(scratch: Scratch, *argv: str, timeout: int = 300) -> dict: + py = scratch.install / "control" / "python" / "python.exe" + out = subprocess.run([str(py), str(scratch.install / "control" / "strata.py"), *argv, "--output", "json"], + env={**scratch.env, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"}, + capture_output=True, text=True, timeout=timeout) + try: + return json.loads(out.stdout) + except ValueError: + return {"ok": False, "raw": out.stdout[-300:] + out.stderr[-300:]} + + +def stop_cli(scratch: Scratch, slot: str) -> dict: + py = scratch.install / "control" / "python" / "python.exe" + out = subprocess.run([str(py), str(scratch.install / "control" / "strata.py"), "runtime", "stop", "--profile", slot, "--wait", "30", + "--output", "json"], env={**scratch.env, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"}, + capture_output=True, text=True, timeout=120) + try: + return json.loads(out.stdout) + except ValueError: + return {"state": "?", "raw": out.stdout[-200:] + out.stderr[-200:]} + + +def case(name: str, install: Path, how: str) -> dict: + with tempfile.TemporaryDirectory(prefix="strata-app-matrix-", ignore_cleanup_errors=True) as tmp: + saved = dict(os.environ) + scratch = Scratch(Path(tmp), install) + app = App(scratch) + problems, note = [], "" + try: + app.wait_up() + slots = ("app-1", "app-2") if how == "two-engines" else ("app-1",) + terminal = None + if how == "window-x-terminal-engine": + # an engine the Terminal started (its own profile, no tie to the app) must survive the app's close + control(scratch, "profile", "create", "terminal-1", "--from-config", str(scratch.models / "strata-stub2.json")) + terminal = control(scratch, "runtime", "start", "--profile", "terminal-1", "--wait", "60") + if terminal.get("state") != "ready": + raise RuntimeError(f"the Terminal's service did not start: {terminal}") + terminal_pids = {r["pid"] for r in procs.records(profile="terminal-1")} | {runtime._read_state("terminal-1")["host_pid"]} + state = app.load("stub") + if how == "two-engines": + state = app.load("stub2", multiple=True) + engine_ports = [i["port"] for i in state["instances"]] + idents, _ = tree_of(app, slots) + kinds = sorted({("engine" if "engine" in " ".join(i.cmd) else "server" if "serve.server" in " ".join(i.cmd) else + "owner" if "strata_control.runtime" in " ".join(i.cmd) else "app" if "strata-desktop" in i.cmd[0].lower() + else "host" if "node" in i.cmd[0].lower() else "other") for i in idents}) + note = f"tree {len(idents)} processes: {', '.join(kinds)}; engine ports {engine_ports}" + t0 = time.monotonic() + if how == "normal-close": + subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True) + elif how in ("window-x", "two-engines", "window-x-terminal-engine"): + hwnd = main_window(app.proc.pid) + if not hwnd: + raise RuntimeError("no main window") + user32.PostMessageW(hwnd, WM_CLOSE, 0, 0) + elif how == "kill-app": + subprocess.run(["taskkill", "/F", "/PID", str(app.proc.pid)], capture_output=True) + elif how == "host-crash": + host = app.host() + subprocess.run(["taskkill", "/F", "/PID", str(host.pid)], capture_output=True) + elif how == "second-launch": + second = subprocess.Popen([str(install / "strata-desktop.exe")], cwd=install, env=scratch.env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + code = second.wait(timeout=30) + except subprocess.TimeoutExpired: + second.kill() + problems.append("the second launch did not exit") + code = None + time.sleep(2) + hosts = [p for p in psutil.process_iter(["name", "pid"]) if p.info["name"].lower() == "node.exe" + and (p.parent() and p.parent().pid == app.proc.pid)] + apps = [p for p in psutil.process_iter(["name"]) if p.info["name"].lower() == "strata-desktop.exe"] + if app.proc.poll() is not None: + problems.append("the first app went away") + if len(apps) != 1: + problems.append(f"{len(apps)} app processes (want 1)") + if len(hosts) != 1: + problems.append(f"{len(hosts)} hosts under the first app (want 1)") + after, _ = tree_of(app, slots) + new = [i for i in after if i.pid not in {x.pid for x in idents}] + if new: + problems.append(f"the second launch started: {[' '.join(i.cmd)[:60] for i in new]}") + note += f"; second launch exit code {code}, app processes {len(apps)}, hosts {len(hosts)}" + subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True) + if how == "host-crash": + # the shell and its window stay (nothing here restarts a dead host); the host, Control's owner, the server and + # the engine must not + idents = [i for i in idents if any(k in " ".join(i.cmd) for k in ("strata_control.runtime", "serve.server", "engine", "node.exe"))] + left = wait_gone(idents, 90) + if left: + problems.append(f"processes left: {left}") + for port in engine_ports: + deadline = time.monotonic() + 10 + while port_open(port) and time.monotonic() < deadline: + time.sleep(0.2) + if port_open(port): + problems.append(f"engine port {port} still open") + if terminal is None and not lease_free(): + problems.append("lease still held") + marks = sorted(p.name for p in scratch.mark.iterdir()) + if terminal is not None: + status = control(scratch, "runtime", "status", "--profile", "terminal-1") + alive_pids = [p for p in terminal_pids if procs.start_token(p)] + if status.get("state") != "ready" or len(alive_pids) != len(terminal_pids): + problems.append(f"closing the app disturbed the Terminal's service: {status.get('state')}, alive {alive_pids} of {sorted(terminal_pids)}") + note += f"; the Terminal's service is {status.get('state')} after the app closed" + stopped = control(scratch, "runtime", "stop", "--profile", "terminal-1", "--wait", "30") + if stopped.get("state") != "stopped" or [p for p in terminal_pids if procs.start_token(p)]: + problems.append(f"the Terminal's service did not stop on request: {stopped}") + time.sleep(1) + if not lease_free(): + problems.append("lease still held after the Terminal's service stopped") + if how in ("normal-close", "window-x", "two-engines", "second-launch", "window-x-terminal-engine") and not ({"quit", "eof"} & set(marks)): + problems.append(f"the engine was not stopped the clean way (marks {marks})") + seconds = round(time.monotonic() - t0, 1) + if how == "host-crash": + subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True) + note += "; the app shell stays open after a host crash (by design today)" + # the slot must be usable again: stopping a lost owner's slot cleans its state; nothing blocks the next load + for slot in slots: + res = stop_cli(scratch, slot) + already = "not managed or is stopped" in json.dumps(res) # nothing was left to stop: the clean outcome + if res.get("state") not in ("stopped",) and not already: + problems.append(f"runtime stop {slot} after the close: {res}") + if runtime._read_state(slot) is not None: + problems.append(f"state of {slot} left behind") + return {"name": f"app-{how}", "ok": not problems, "problems": problems, "seconds": seconds, "marks": marks, "note": note} + except Exception as exc: # noqa: BLE001 + return {"name": f"app-{how}", "ok": False, "problems": [f"{type(exc).__name__}: {exc}"] + problems, "note": note} + finally: + for p in psutil.process_iter(["name", "exe"]): + try: + if (p.info["exe"] or "").lower().startswith(str(install).lower()): + p.kill() + except psutil.Error: + pass + for r in procs.records(): + try: + psutil.Process(r["pid"]).kill() + except psutil.Error: + pass + os.environ.clear(); os.environ.update(saved) + + +SCENARIOS = ["normal-close", "window-x", "window-x-terminal-engine", "kill-app", "host-crash", "second-launch", "two-engines"] + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--install", required=True) + ap.add_argument("--scenarios", default="all") + ap.add_argument("--report") + a = ap.parse_args() + names = SCENARIOS if a.scenarios == "all" else a.scenarios.split(",") + results = [] + for how in names: + r = case(how, Path(a.install), how) + results.append(r) + print(("PASS " if r["ok"] else "FAIL ") + r["name"], r.get("seconds", ""), r.get("problems") or "", r.get("note", ""), flush=True) + if a.report: + Path(a.report).write_text(json.dumps({"platform": "windows", "engine": "fake", "results": results}, indent=1), encoding="utf-8") + return 0 if all(r["ok"] for r in results) else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/desktop/scripts/cards-e2e.mjs b/apps/desktop/scripts/cards-e2e.mjs new file mode 100644 index 00000000000..fe31a7f452f --- /dev/null +++ b/apps/desktop/scripts/cards-e2e.mjs @@ -0,0 +1,110 @@ +#!/usr/bin/env node +/** + * The Graphics cards choice of the app, end to end on a box with two cards, through the installed app layout (packaged host + bundled Control + a real + * engine component): the model list carries the options (one rule, strata_control/gpu_fit.py), a model that fits one card recommends that card, then + * load with ONE card -> answers, only that card holds the model; load with BOTH cards (the layer split) -> answers, both cards hold the model. + * + * node cards-e2e.mjs --install --components > --work \ + * --family qwen --model IQ3_XXS --data [--smi "nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits"] + */ +import { spawn, spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, readdirSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { join, resolve } from 'node:path'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]]] : acc), [])); +for (const need of ['install', 'components', 'work', 'model']) if (!args[need]) { console.error('missing --' + need); process.exit(2); } +const install = resolve(args.install), work = resolve(args.work), components = resolve(args.components), family = String(args.family ?? 'qwen'), modelId = String(args.model); +const node = join(install, 'node', 'node'), hostEntry = join(install, 'host', 'server', 'index.mjs'); +const dirs = { models: join(work, 'models'), profiles: join(work, 'profiles'), runtime: join(work, 'runtime'), home: join(work, 'home'), xdg: join(work, 'xdg'), appdata: join(work, 'appdata') }; +for (const d of [dirs.models, dirs.home, dirs.xdg, dirs.appdata]) mkdirSync(d, { recursive: true }); +const delay = ms => new Promise(r => setTimeout(r, ms)); +let failed = false; +const record = (name, ok, detail = '') => { if (!ok) failed = true; console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + String(detail).slice(0, 500) : ''}`); }; +const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; +const env = { ...process.env, STRATA_COMPONENTS_DIR: components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_INSTALL_DIR: dirs.models, + STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models-unused'), APPDATA: dirs.appdata, XDG_CONFIG_HOME: dirs.xdg, PYTHONDONTWRITEBYTECODE: '1' }; +delete env.STRATA_API_KEY; +const port = await freePort(); +const base = `http://127.0.0.1:${port}`; +const host = spawn(node, [hostEntry], { cwd: join(install, 'host'), stdio: ['ignore', 'pipe', 'pipe'], + env: { ...env, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', + STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } }); +let hostLog = ''; +host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; }); +const call = async (path, method = 'GET', body) => { + const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); + return { status: response.status, body: await response.json().catch(() => null) }; +}; +async function waitJob(id, seconds) { + let last = ''; + for (let i = 0; i < seconds * 2; i++) { + const state = (await call('/api/native')).body; + const job = state.jobs.find(j => j.id === id); + if (job && job.summary !== last) { last = job.summary; console.log(' ... ' + String(last).slice(0, 120)); } + if (job && job.state !== 'running') return { job, state }; + await delay(500); + } + throw new Error('operation did not finish'); +} +const smi = () => { + const cmd = String(args.smi ?? 'nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits').split(' '); + const r = spawnSync(cmd[0], cmd.slice(1), { encoding: 'utf8' }); + return (r.stdout ?? '').split('\n').map(s => Number(s.trim())).filter(Number.isFinite); +}; +async function chatPong(instance) { + const chat = await call('/v1/chat/completions', 'POST', { model: instance?.apiModelId ?? modelId.toLowerCase(), max_tokens: 400, stream: false, temperature: 0, messages: [{ role: 'user', content: 'Reply with exactly one word: pong' }] }); + const m = chat.body?.choices?.[0]?.message ?? {}; + return { ok: chat.status === 200 && /pong/i.test(`${m.content ?? ''}`), text: `${m.content ?? ''}`.slice(0, 60), status: chat.status }; +} +async function main() { + let up = false; + for (let i = 0; i < 200 && !up; i++) { try { up = (await fetch(base + '/api/health')).ok; } catch { /* not yet */ } if (!up) await delay(150); } + record('host healthy', up, up ? base : hostLog.slice(-500)); + if (!up) return; + const packages = existsSync(join(components, 'engine')) ? readdirSync(join(components, 'engine')) : []; + record('an engine component is installed', packages.length > 0, packages.join(', ')); + + // ---- the model list carries the choice + const native = (await call('/api/native?refresh=1')).body; + const gpus = native.hardware?.gpus ?? []; + record('the host sees two or more graphics cards', gpus.filter(g => g.usable !== false).length >= 2, JSON.stringify(gpus.map(g => ({ i: g.index, n: g.name, gb: g.vram_gb })))); + const size = native.catalog?.families?.find(f => f.family === family)?.sizes.find(s => s.model === modelId); + const opt = size?.gpu_options; + record('the model list offers the cards choice for this model', !!opt && opt.options.length >= 2, JSON.stringify(opt?.options?.map(o => ({ key: o.key, cards: o.cards, verdict: o.verdict, rec: o.recommended })))); + record('a model that fits one card recommends the single largest card (the split is offered, not forced)', opt?.recommended === 'single' && opt.options.find(o => o.key === 'split'), `recommended=${opt?.recommended}`); + const single = opt?.options.find(o => o.key === 'single')?.cards ?? [0]; + const both = opt?.options.find(o => o.key === 'split')?.cards ?? [0, 1]; + + // ---- Download and prepare with the recommended card + const values = { family, model: modelId, context: 32768, vision: 'no', gpu: single[0], ...(args.data ? { data_dir: resolve(args.data) } : {}) }; + const started = await call('/api/native/operations', 'POST', { kind: 'install', args: values }); + record('the install operation starts', started.status === 200 || started.status === 202, JSON.stringify(started.body).slice(0, 160)); + const done = await waitJob(started.body.id, 3600); + record('Download and prepare finishes', done.job.state === 'done', `${done.job.state} ${done.job.error ?? done.job.summary}`); + const installed = (await call('/api/native?refresh=1')).body.installed?.models?.find(m => String(m.model).toLowerCase() === modelId.toLowerCase()); + const model = installed?.model ?? modelId.toLowerCase(); + + for (const [label, cards] of [['ONE card', single], ['BOTH cards (layer split)', both]]) { + const before = smi(); + const load = await call('/api/native/operations', 'POST', { kind: 'load', args: { model, gpus: cards } }); + const loaded = await waitJob(load.body.id, 900); + const instance = loaded.state.instances[0]; + record(`load with ${label} starts the engine`, loaded.job.state === 'done' && instance?.status === 'ready', `${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}; gpus=${JSON.stringify(instance?.gpus)}`); + record(`the instance runs on exactly the chosen card(s)`, JSON.stringify([...(instance?.gpus ?? [])].sort()) === JSON.stringify([...cards].sort()), `want ${JSON.stringify(cards)} got ${JSON.stringify(instance?.gpus)}`); + await delay(3000); + const used = smi(); + const holding = used.map((mb, i) => (mb - (before[i] ?? 0)) > 1000 ? i : -1).filter(i => i >= 0); + record(`only the chosen card(s) hold the model (graphics memory in use: ${used.join(', ')} MiB)`, JSON.stringify(holding) === JSON.stringify([...cards].sort()), `holding ${JSON.stringify(holding)}`); + const pong = await chatPong(instance); + record(`it answers (${label})`, pong.ok, `${pong.status} ${JSON.stringify(pong.text)}`); + const unloaded = await call(`/api/native/instances/${instance?.id}/unload`, 'POST', {}); + record(`unload (${label})`, unloaded.status === 200, unloaded.status); + await delay(4000); + } +} +try { await main(); } catch (e) { record('run', false, e.stack ?? e); } +host.kill(); +await delay(1500); +console.log(failed ? 'CARDS-E2E FAIL' : 'CARDS-E2E PASS'); +process.exit(failed ? 1 : 0); diff --git a/apps/desktop/scripts/fetch-node.ps1 b/apps/desktop/scripts/fetch-node.ps1 new file mode 100644 index 00000000000..2d833a9bf05 --- /dev/null +++ b/apps/desktop/scripts/fetch-node.ps1 @@ -0,0 +1,72 @@ +# Fetch and verify the private Node runtime the Windows desktop bundle ships (win-x64). +# +# The PowerShell twin of fetch-node.sh: same pinned version, same SHA-256 pin, same refusal to +# install anything whose digest does not match. Not committed output: node.exe is a ~90 MB binary. +# +# Usage: +# powershell -NoProfile -ExecutionPolicy Bypass -File apps\desktop\scripts\fetch-node.ps1 +# ... -File fetch-node.ps1 -Check # verify what is already installed +# ... -File fetch-node.ps1 -FromFile node.zip # verify and install a zip you already have (offline) +# +# The Node version must satisfy the App Host's own engines.node (>= 24.12.0). +[CmdletBinding()] +param( + [switch]$Check, + [string]$FromFile = '', + [string]$Dest = '' +) +$ErrorActionPreference = 'Stop' + +$NodeVersion = if ($env:STRATA_NODE_VERSION) { $env:STRATA_NODE_VERSION } else { '24.12.0' } +$Target = 'win-x64' +# SHA-256 of node-v24.12.0-win-x64.zip from nodejs.org's SHASUMS256.txt; keep equal to fetch-node.sh. +$Expected = '9c125f61ae947b52e779095830f9cac267846a043ef7192183c84016aaad2812' +if (-not $Dest) { $Dest = Join-Path $PSScriptRoot '..\src-tauri\resources\node' } +$Installed = Join-Path $Dest 'node.exe' + +function Fail([string]$Message) { [Console]::Error.WriteLine("fetch-node: $Message"); exit 1 } + +if ($Check) { + if (-not (Test-Path -LiteralPath $Installed)) { Fail "not installed at $Installed" } + $got = (& $Installed --version).Trim() + Write-Output "fetch-node: $Installed is $got" + if ($got -ne "v$NodeVersion") { Fail "expected v$NodeVersion" } + exit 0 +} + +$Archive = "node-v$NodeVersion-$Target.zip" +$Work = Join-Path ([IO.Path]::GetTempPath()) ("strata-node-" + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $Work | Out-Null +try { + $Zip = Join-Path $Work $Archive + if ($FromFile) { + Copy-Item -LiteralPath $FromFile -Destination $Zip + } else { + $Url = "https://nodejs.org/dist/v$NodeVersion/$Archive" + Write-Output "fetch-node: $Url" + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + $ProgressPreference = 'SilentlyContinue' + Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Zip + } + $Actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $Zip).Hash.ToLowerInvariant() + if ($NodeVersion -ne '24.12.0') { + # another version has no recorded digest: say so rather than implying a verification + [Console]::Error.WriteLine("fetch-node: WARNING - no recorded digest for v$NodeVersion; this download is NOT authenticated.") + [Console]::Error.WriteLine("fetch-node: computed sha256 $Actual - record it in this script and fetch-node.sh.") + } elseif ($Actual -ne $Expected) { + Fail "REFUSING - $Archive hashes $Actual, expected $Expected" + } else { + Write-Output 'fetch-node: sha256 verified against the recorded digest' + } + Add-Type -AssemblyName System.IO.Compression.FileSystem + $zipFile = [IO.Compression.ZipFile]::OpenRead($Zip) + try { + $entry = $zipFile.GetEntry("node-v$NodeVersion-$Target/node.exe") + if (-not $entry) { Fail "node.exe is not inside $Archive" } + New-Item -ItemType Directory -Force -Path $Dest | Out-Null + [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $Installed, $true) + } finally { $zipFile.Dispose() } + Write-Output "fetch-node: installed at $Installed" +} finally { + Remove-Item -LiteralPath $Work -Recurse -Force -ErrorAction SilentlyContinue +} diff --git a/apps/desktop/scripts/fetch-node.sh b/apps/desktop/scripts/fetch-node.sh new file mode 100755 index 00000000000..3a363233e2e --- /dev/null +++ b/apps/desktop/scripts/fetch-node.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# Fetch and verify the private Node runtime the desktop bundle ships. +# +# The App Host is an ordinary Node program, and the packaging requirement is that an end user +# supplies no runtime of their own. The desktop bundle therefore carries a pinned standalone Node +# beside the host. +# +# It is NOT committed. It is a ~117 MB platform binary: committing it would bloat every clone, it +# cannot be reviewed in a diff, and it is not source. This script is the reproducible substitute — +# it downloads the official build for the target and refuses to install anything whose SHA-256 does +# not match the recorded digest. +# +# Usage: +# apps/desktop/scripts/fetch-node.sh # host platform +# apps/desktop/scripts/fetch-node.sh --target linux-x64 +# apps/desktop/scripts/fetch-node.sh --check # verify what is already installed +# +# The Node version must satisfy the App Host's own `engines.node` (>= 24.12.0). +set -euo pipefail + +NODE_VERSION="${STRATA_NODE_VERSION:-24.12.0}" +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DEST="$HERE/../src-tauri/resources/node" + +# Published SHA-256 of each official nodejs.org archive, recorded so a tampered or truncated +# download is refused rather than shipped. Add a row when bumping the version. +# Taken from nodejs.org's own SHASUMS256.txt for v24.12.0, which is published over HTTPS beside +# the archives. Recorded here so the fetch is verified against a value that does not come from the +# same response as the payload. +digest_for() { + case "$1" in + darwin-arm64) echo "319f221adc5e44ff0ed57e8a441b2284f02b8dc6fc87b8eb92a6a93643fd8080" ;; + linux-x64) echo "6159227e0af7d7c3c6bb2fa900452b04a6cb8841a702a79acc613209d70b04d0" ;; + linux-arm64) echo "9b2a2eeb98a8eb37361224e2a1d060300ad2dd143af58dfdb16de785df0f1228" ;; + win-x64) echo "9c125f61ae947b52e779095830f9cac267846a043ef7192183c84016aaad2812" ;; + *) echo "" ;; + esac +} + +target() { + if [ "${1:-}" = "--target" ]; then echo "${2:?--target needs a value}"; return; fi + case "$(uname -s)-$(uname -m)" in + Darwin-arm64) echo darwin-arm64 ;; + Linux-x86_64) echo linux-x64 ;; + Linux-aarch64) echo linux-arm64 ;; + MINGW*|MSYS*|CYGWIN*) echo win-x64 ;; + *) echo "unsupported host: $(uname -s)-$(uname -m)" >&2; exit 2 ;; + esac +} + +TARGET="$(target "$@")" +EXE="node" +case "$TARGET" in win-*) EXE="node.exe" ;; esac +INSTALLED="$DEST/$EXE" + +if [ "${1:-}" = "--check" ]; then + if [ ! -x "$INSTALLED" ]; then echo "fetch-node: not installed at $INSTALLED" >&2; exit 1; fi + got="$("$INSTALLED" --version)" + echo "fetch-node: $INSTALLED is $got" + case "$got" in "v$NODE_VERSION") exit 0 ;; *) echo "fetch-node: expected v$NODE_VERSION" >&2; exit 1 ;; esac +fi + +# The official archive for this target. +case "$TARGET" in + darwin-arm64) ARCHIVE="node-v$NODE_VERSION-darwin-arm64.tar.gz" ;; + darwin-x64) ARCHIVE="node-v$NODE_VERSION-darwin-x64.tar.gz" ;; + linux-x64) ARCHIVE="node-v$NODE_VERSION-linux-x64.tar.gz" ;; + linux-arm64) ARCHIVE="node-v$NODE_VERSION-linux-arm64.tar.gz" ;; + win-x64) ARCHIVE="node-v$NODE_VERSION-win-x64.zip" ;; + *) echo "fetch-node: no archive known for $TARGET" >&2; exit 2 ;; +esac +URL="https://nodejs.org/dist/v$NODE_VERSION/$ARCHIVE" + +EXPECTED="$(digest_for "$TARGET")" +WORK="$(mktemp -d "${TMPDIR:-/tmp}/strata-node.XXXXXX")" # GNU mktemp needs the X template; BSD accepts it too +trap 'rm -rf "$WORK"' EXIT + +echo "fetch-node: $URL" +curl -fsSL -o "$WORK/$ARCHIVE" "$URL" + +ACTUAL="$(shasum -a 256 "$WORK/$ARCHIVE" 2>/dev/null | cut -d' ' -f1 || sha256sum "$WORK/$ARCHIVE" | cut -d' ' -f1)" +if [ -n "$EXPECTED" ]; then + if [ "$ACTUAL" != "$EXPECTED" ]; then + echo "fetch-node: REFUSING — $ARCHIVE hashes $ACTUAL, expected $EXPECTED" >&2 + exit 1 + fi + echo "fetch-node: sha256 verified against the recorded digest" +else + # Without a recorded digest the download cannot be authenticated. Say so loudly and keep the + # computed value so it can be recorded, rather than implying a verification that did not happen. + echo "fetch-node: WARNING — no recorded digest for $TARGET; this download is NOT authenticated." >&2 + echo "fetch-node: computed sha256 $ACTUAL — record it in $(basename "${BASH_SOURCE[0]}") to enable verification." >&2 +fi + +mkdir -p "$DEST" +case "$ARCHIVE" in + *.zip) unzip -q -j "$WORK/$ARCHIVE" "node-v$NODE_VERSION-win-x64/node.exe" -d "$DEST" ;; + *) tar xzf "$WORK/$ARCHIVE" -C "$WORK" + cp "$WORK/node-v$NODE_VERSION-$TARGET/bin/node" "$DEST/node" ;; +esac +chmod +x "$DEST/$EXE" + +echo "fetch-node: installed $("$DEST/$EXE" --version) at $DEST/$EXE" diff --git a/apps/desktop/scripts/first-run-ui.mjs b/apps/desktop/scripts/first-run-ui.mjs new file mode 100644 index 00000000000..757905cd2d0 --- /dev/null +++ b/apps/desktop/scripts/first-run-ui.mjs @@ -0,0 +1,121 @@ +#!/usr/bin/env node +/** + * The first run of the installed app, headless: the host as the Tauri shell starts it (STRATA_PACKAGED=1, STRATA_NO_ACQUIRE=1, + * the staged Control, nothing installed, nothing in the per-user folders) and Chrome on its onboarding. + * + * node apps/desktop/scripts/first-run-ui.mjs [--control ] [--node ] [--work ] [--shots ] + * + * Checks, one line each (exit 1 if any fails): + * the host answers; /api/native has a real catalog (families with sizes), a recommendation and the GPUs of this PC + * (from Control's bundled installer on Control's Python); the page shows "Let's get started", and after it the model + * list with sizes (no "couldn't show this screen"); no page error; the install plan for the recommended model is a + * plan (nothing is downloaded or started: a plan changes nothing); the spy sees no pip/git/compiler/engine fetch. + * Per-user folders (STRATA_HOME, APPDATA, LOCALAPPDATA, the components and install folders) are all under --work. + * No model is downloaded and no engine runs. + */ +import { spawn } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') ? true : all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const repoHost = resolve(here, '../../host'); +const staged = resolve(here, '../src-tauri/resources'); +const control = resolve(args.control ?? join(staged, 'control')); +const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'win32' ? 'node.exe' : 'node')); +const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'strata-first-run-'))); +const shots = resolve(args.shots ?? join(work, 'shots')); +mkdirSync(work, { recursive: true }); mkdirSync(shots, { recursive: true }); +const spy = pathToFileURL(join(repoHost, 'tests/helpers/acquire-spy.mjs')).href; +const spyLog = join(work, 'spy.log'); writeFileSync(spyLog, ''); + +const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find(existsSync); + +let failed = false; +const check = (ok, label, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${detail ? ' ' + detail : ''}`); if (!ok) failed = true; }; +const delay = ms => new Promise(r => setTimeout(r, ms)); +const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; + +for (const need of [nodeExe, join(control, 'strata.py'), join(repoHost, 'dist', 'index.html')]) if (!existsSync(need)) { console.error(`missing ${need} (run stage-control.py, fetch-node and "npm run build" in apps/host first)`); process.exit(2); } + +const dirs = { home: join(work, 'home'), appdata: join(work, 'appdata'), local: join(work, 'local'), components: join(work, 'local', 'Strata', 'components') }; +for (const d of Object.values(dirs)) mkdirSync(d, { recursive: true }); +const port = await freePort(); +const env = { + ...process.env, + STRATA_PORT: String(port), STRATA_DIST: join(repoHost, 'dist'), STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', + STRATA_CONTROL_DIR: control, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models'), STRATA_COMPONENTS_DIR: dirs.components, + APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, XDG_CONFIG_HOME: join(work, 'xdg'), XDG_DATA_HOME: join(work, 'xdgdata'), + STRATA_PROFILE_DIR: join(work, 'profiles'), STRATA_RUNTIME_DIR: join(work, 'runtime'), ACQUIRE_SPY_LOG: spyLog, +}; +delete env.STRATA_INSTALL_DIR; +mkdirSync(env.STRATA_MODELS_DIR, { recursive: true }); +const host = spawn(nodeExe, [...(args['no-spy'] === undefined ? ['--import', spy] : []), join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, env, stdio: ['ignore', 'pipe', 'pipe'] }); +let hostLog = ''; +host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; }); +const base = `http://127.0.0.1:${port}`; +const api = async (path, init) => { const r = await fetch(base + path, init); return { status: r.status, body: await r.json().catch(() => null) }; }; + +let browser; +try { + let up = false; + for (let i = 0; i < 150 && !up; i++) { try { up = (await api('/api/health')).status === 200; } catch { await delay(200); } } + check(up, 'the packaged host starts', `port ${port}`); + if (!up) throw new Error(hostLog.slice(-2000)); + + const native = await api('/api/native?refresh=1'); + const state = native.body; + check(native.status === 200 && state?.available === true, 'the host reads Control', state?.error ?? ''); + const sizes = (state?.catalog?.families ?? []).reduce((n, f) => n + (f.sizes?.length ?? 0), 0); + check((state?.catalog?.families?.length ?? 0) > 0 && sizes >= 3, 'the catalog has real families and sizes', `${state?.catalog?.families?.length} families, ${sizes} sizes`); + check(!!state?.catalog?.recommendation, 'the catalog has a recommendation', JSON.stringify(state?.catalog?.recommendation ?? null).slice(0, 120)); + check(Array.isArray(state?.hardware?.gpus), 'the hardware lists GPUs', (state?.hardware?.gpus ?? []).map(g => `${g.name} ${g.vram_gb} GB`).join('; ') || 'none on this PC'); + check(state?.installDir && realpathSync.native(state.installDir).toLowerCase().startsWith(realpathSync.native(work).toLowerCase()), 'models go to a writable per-user folder, not the bundle', state?.installDir); + const hw = (await api('/api/hardware')).body; + console.log('info host hardware probe:', JSON.stringify((hw?.gpus ?? []).map(g => ({ name: g.name, backend: g.backend, vramGb: g.vramGb, unified: g.unified })))); + check(!state?.installerError, 'the bundled installer answers', state?.installerError ?? ''); + + browser = await chromium.launch({ executablePath: CHROME, headless: true }); + const page = await browser.newPage({ viewport: { width: 1400, height: 950 } }); + const problems = []; + page.on('pageerror', e => problems.push(`pageerror: ${e.message}`)); + await page.goto(base, { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('text=/Let.s get started|Choose a version|Connect your Strata/i', { timeout: 30000 }).catch(() => {}); + await page.screenshot({ path: join(shots, '1-welcome.png') }); + const broken = await page.locator('text=/couldn.t show this screen/i').count(); + check(broken === 0, 'the first screen renders (not "Strata couldn\'t show this screen")'); + const start = page.getByRole('button', { name: /get started/i }); + check(await start.count() > 0, 'the welcome step offers "Let\'s get started"'); + if (await start.count()) await start.first().click(); + await page.waitForSelector('text=/Choose a version/i', { timeout: 30000 }).catch(() => {}); + await delay(1200); + await page.screenshot({ path: join(shots, '2-models.png') }); + check(await page.locator('text=/couldn.t show this screen/i').count() === 0, 'the model step renders'); + check(await page.getByText(/Choose a version/i).count() > 0, 'the model step lists the versions'); + const labels = await page.locator('[role=radio]').allInnerTexts(); + check(labels.length >= 3, 'the versions are the real catalog\'s sizes', labels.map(l => l.replace(/\s+/g, ' ').slice(0, 40)).join(' | ')); + check(labels.some(l => /\d+\.\d\s*GB/.test(l)), 'each version shows its download size'); + check(problems.length === 0, 'no page error', problems.join('; ')); + + const recommended = state?.catalog?.recommendation; + if (recommended?.model) { + const plan = await api('/api/native/plan', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ family: recommended.family, model: recommended.model, context: recommended.context, data_dir: join(work, 'Strata-data') }) }); + check(plan.status === 200 && !!plan.body?.plan, 'the install plan for the recommended model is a plan (nothing downloaded)', plan.body?.summary?.slice(0, 100) ?? JSON.stringify(plan.body).slice(0, 150)); + check(!existsSync(join(work, 'Strata-data', 'models')), 'a plan wrote no model files'); + } +} catch (error) { + check(false, 'the run', String(error?.message ?? error).slice(0, 600)); +} finally { + await browser?.close().catch(() => {}); + host.kill(); + await new Promise(r => host.once('exit', r)); // only the PID this script started + const attempts = readFileSync(spyLog, 'utf8').split('\n').filter(Boolean); + check(attempts.length === 0, 'the spy saw no pip, git, compiler, engine or internet access', attempts.slice(0, 3).join(' ')); + console.log(`shots in ${shots}`); + if (!args.work) rmSync(work, { recursive: true, force: true, maxRetries: 3 }); +} +process.exit(failed ? 1 : 0); diff --git a/apps/desktop/scripts/flatten-pnpm.mjs b/apps/desktop/scripts/flatten-pnpm.mjs new file mode 100644 index 00000000000..403d4df271c --- /dev/null +++ b/apps/desktop/scripts/flatten-pnpm.mjs @@ -0,0 +1,133 @@ +/** + * Turn a pnpm "isolated" node_modules (a virtual store in `.pnpm` full of links) into an ordinary hoisted tree of real folders. + * + * Why: the installer copies the Harness folder file by file. pnpm's layout is thousands of links (junctions on Windows); a copy + * that follows them duplicates every package once per dependent and one that does not breaks on the first dangling link. A hoisted + * tree has each package once (nested only where two versions of the same name are needed), no links, and Node resolves it + * exactly as it resolves any npm install. + * + * Algorithm (the one npm uses, in short): the packages the root names come first, at the top. Then, walking each placed package's + * own dependencies: look the name up from the package's own folder upwards; if the same instance is already visible, nothing to + * do; if a DIFFERENT instance of that name is visible, nest this one inside the dependent; if none is visible, hoist it to the top. + * + * @param {string} out folder holding `node_modules` + * @param {{skip?: RegExp}} [options] package names never copied (the caller removes them anyway) + * @returns {{packages:number, copied:number, nested:number}} + */ +import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync } from 'node:fs'; +import { dirname, join, relative, sep } from 'node:path'; + +export function flattenPnpm(out, { skip = null } = {}) { + const nm = join(out, 'node_modules'); + const store = join(nm, '.pnpm'); + const flatRoot = join(out, 'node_modules.flat'); + rmSync(flatRoot, { recursive: true, force: true }); + mkdirSync(join(flatRoot, 'node_modules'), { recursive: true }); + + const manifest = dir => { try { return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')); } catch { return null; } }; + const nameOf = dir => manifest(dir)?.name ?? null; + /** + * What makes two instances "the same package": name and version. pnpm keeps one copy per set of peer packages (the same workspace + * package under many hashed folders); in one hoisted tree they are one package. + */ + const identity = dir => { const m = manifest(dir); return m ? `${m.name}@${m.version}` : dir; }; + /** The sibling links of a store instance: its dependencies, by name -> real instance folder. */ + function storeDeps(instance, name) { + const container = name.startsWith('@') ? dirname(dirname(instance)) : dirname(instance); + const found = new Map(); + for (const e of readdirSync(container, { withFileTypes: true })) { + if (e.name === '.bin') continue; + const entries = e.name.startsWith('@') ? readdirSync(join(container, e.name), { withFileTypes: true }).map(x => [`${e.name}/${x.name}`, join(container, e.name, x.name)]) : [[e.name, join(container, e.name)]]; + for (const [dep, p] of entries) { + if (dep === name) continue; + try { if (lstatSync(p).isSymbolicLink() || existsSync(p)) found.set(dep, realpathSync(p)); } catch { /* a dangling link: the package was removed on purpose */ } + } + } + return found; + } + /** Every instance in the store by package name, for packages that arrived without a store entry (copied peers). */ + const byName = new Map(); + if (existsSync(store)) { + for (const id of readdirSync(store, { withFileTypes: true })) { + if (!id.isDirectory()) continue; + const container = join(store, id.name, 'node_modules'); + if (!existsSync(container)) continue; + for (const e of readdirSync(container, { withFileTypes: true })) { + if (e.name === '.bin') continue; + const dirs = e.name.startsWith('@') ? readdirSync(join(container, e.name)).map(x => join(container, e.name, x)) : [join(container, e.name)]; + for (const d of dirs) { + let real; try { real = realpathSync(d); } catch { continue; } + if (!real.startsWith(store)) continue; // a link to a workspace package outside the store is handled through the instance table + const n = nameOf(real); + if (n && !byName.has(n)) byName.set(n, real); + } + } + } + } + + const placed = new Map(); // folder (in the flat tree) -> real instance folder it holds + let copied = 0, nested = 0; + + const visibleFrom = (chain, name) => { + for (const dir of chain) { + const slot = join(dir, 'node_modules', ...name.split('/')); + if (placed.has(slot)) return { slot, instance: placed.get(slot) }; + } + return null; + }; + const copyInto = (slot, instance) => { + mkdirSync(dirname(slot), { recursive: true }); + cpSync(instance, slot, { recursive: true, dereference: true, filter: f => !relative(instance, f).split(sep).includes('node_modules') }); + placed.set(slot, identity(instance)); + copied++; + }; + + const queue = []; // { slotDir (folder of the placed package), chain (folders searched upwards), instance, name } + const rootChain = [flatRoot]; + const place = (name, instance, chain, forceHere) => { + if (skip?.test(name)) return; + const seen = visibleFrom(chain, name); + if (seen && seen.instance === identity(instance)) return; + const hoist = !seen && !forceHere; + const base = hoist ? flatRoot : chain[0]; + const slot = join(base, 'node_modules', ...name.split('/')); + if (placed.has(slot)) return; // another instance already sits where this one would go (it nests below, handled by the caller's chain) + copyInto(slot, instance); + if (!hoist && base !== flatRoot) nested++; + queue.push({ slotDir: slot, chain: [slot, ...(hoist ? rootChain : chain)], instance, name }); + }; + + // 1. the packages the root names + const rootEntries = []; + for (const e of readdirSync(nm, { withFileTypes: true })) { + if (e.name === '.pnpm' || e.name === '.bin' || e.name.startsWith('.')) continue; + const entries = e.name.startsWith('@') ? readdirSync(join(nm, e.name)).map(x => [`${e.name}/${x}`, join(nm, e.name, x)]) : [[e.name, join(nm, e.name)]]; + for (const [name, p] of entries) rootEntries.push([name, p]); + } + for (const [name, p] of rootEntries) { + let real; try { real = realpathSync(p); } catch { continue; } + place(name, real, rootChain, true); + } + // 2. their dependencies, breadth first + while (queue.length) { + const { slotDir, chain, instance, name } = queue.shift(); + let wants; + if (instance.startsWith(store)) wants = storeDeps(instance, name); + else { + // a package copied in without a store entry: its declared requirements, taken from the store by name when not visible yet + const m = manifest(instance) ?? {}; + wants = new Map(); + for (const dep of [...Object.keys(m.dependencies ?? {}), ...Object.keys(m.peerDependencies ?? {}), ...Object.keys(m.optionalDependencies ?? {})]) { + if (visibleFrom(chain, dep)) continue; + const real = byName.get(dep); + if (real) wants.set(dep, real); + } + } + for (const [dep, real] of wants) place(dep, real, chain, false); + } + + rmSync(nm, { recursive: true, force: true }); + renameSync(join(flatRoot, 'node_modules'), nm); + rmSync(flatRoot, { recursive: true, force: true }); + return { packages: placed.size, copied, nested }; +} diff --git a/apps/desktop/scripts/harness-budget.mjs b/apps/desktop/scripts/harness-budget.mjs new file mode 100644 index 00000000000..4f588d756b7 --- /dev/null +++ b/apps/desktop/scripts/harness-budget.mjs @@ -0,0 +1,52 @@ +/** Strata's output-budget correction for the staged pi-ai copy. */ +import { createHash } from 'node:crypto'; +import { lstatSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +export const HARNESS_BUDGET_PATCH = Object.freeze({ + id: 'strata-pi-ai-context-safety-v2', + package: '@earendil-works/pi-ai', + version: '1.1.0', + file: 'node_modules/@earendil-works/pi-ai/dist/api/simple-options.js', + beforeSha256: '9b3cc0ae6daa86fdc050bc0cb0f3f986401e64ccddbde6757183c9f8ad411be2', +}); + +const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); +const oldClamp = 'const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;'; +// Small windows also need room after tool results; a fixed margin must not +// consume all remaining estimated space. Keep the old 64K+ calculation. +const newClamp = `const remaining = model.contextWindow - estimateContextTokens(context).tokens; + const safety = model.contextWindow >= 65536 ? CONTEXT_SAFETY_TOKENS + : Math.min(CONTEXT_SAFETY_TOKENS, Math.floor(model.contextWindow / 16), Math.max(0, Math.floor(remaining / 2))); + const available = remaining - safety;`; + +/** + * Patch only a flattened, disposable staged Harness. Returns the BUNDLE.json + * provenance entry; the caller records it when writing the bundle manifest. + * A repeat application or any unknown package/source fails before writing. + */ +export function patchStagedHarnessBudget(stagedRoot) { + const fail = message => { throw new Error(`Harness output-budget patch: ${message}`); }; + const root = realpathSync(resolve(stagedRoot)); + const packageDir = join(root, 'node_modules', '@earendil-works', 'pi-ai'); + const target = join(root, HARNESS_BUDGET_PATCH.file); + let manifest, before; + try { + manifest = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8')); + // Flattening must have removed links; never write through a shared source file. + if (realpathSync(target) !== target || !lstatSync(target).isFile() || lstatSync(target).nlink !== 1) + fail('expected an unlinked staged module'); + before = readFileSync(target); + } catch (error) { + fail(`cannot read a standalone staged pi-ai dependency (${error.message})`); + } + if (manifest?.name !== HARNESS_BUDGET_PATCH.package || manifest?.version !== HARNESS_BUDGET_PATCH.version) + fail('expected @earendil-works/pi-ai 1.1.0; review the patch before staging a different dependency'); + if (sha256(before) !== HARNESS_BUDGET_PATCH.beforeSha256) + fail('unexpected simple-options.js SHA-256; review the dependency source before staging'); + const source = before.toString('utf8'); + if (source.split(oldClamp).length !== 2) fail('expected exactly one known context clamp'); + const after = Buffer.from(source.replace(oldClamp, newClamp)); + writeFileSync(target, after); + return { ...HARNESS_BUDGET_PATCH, afterSha256: sha256(after) }; +} diff --git a/apps/desktop/scripts/harness-prune.mjs b/apps/desktop/scripts/harness-prune.mjs new file mode 100644 index 00000000000..35b8112447f --- /dev/null +++ b/apps/desktop/scripts/harness-prune.mjs @@ -0,0 +1,79 @@ +/** + * Which files and folders of the staged Harness are dropped, and the check that nothing the Harness imports is gone. + * + * The 2026-10-17 tester report: on Linux and Mac every agent chat failed ("session/create ... waiting for workflowEngine"). + * Cause: the old rule "drop any folder named after another operating system" also removed the Harness's own JavaScript package + * `@deepseek-ai/dsh-win32-process`. It is plain JS (no binary), and `dsh-subprocess-local` and `dsh-sandbox-local` import it by + * name on every platform, so those two plugins failed to load, and everything waiting on them (shell, subprocess, ptcRuntime, + * workflowEngine) never started. Windows kept it (the rule differs there), so the Windows tests passed. + */ +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { join, sep } from 'node:path'; + +export const OTHER_OS = { + win32: /(^|[\\/._-])(darwin|linux|android|freebsd|musl)([\\/._-]|$)/i, + darwin: /(^|[\\/._-])(win32|linux|android|freebsd|musl)([\\/._-]|$)/i, + // Linux: the AppImage bundler (linuxdeploy) resolves the libraries of every ELF file under resources and stops on one it + // cannot satisfy (koffi's musl build wants libc.musl). The app is glibc x86_64, so musl and other-CPU builds are dropped. + linux: /(^|[\\/._-])(win32|darwin|android|freebsd|musl|arm64|aarch64|armv7|arm|ia32|riscv64|ppc64|s390x|loong64)([\\/._-]|$)/i, +}; +const NATIVE_FOLDER = /prebuild|bin|native|platform|-(win32|darwin|linux)/i; + +/** The Harness's own JavaScript packages (`@deepseek-ai/dsh-*`) are code every platform imports by name; never drop one. */ +export function isHarnessCodePackage(path) { + const parts = path.split(sep); + const i = parts.lastIndexOf('@deepseek-ai'); + return i >= 0 && i === parts.length - 2 && parts[i + 1].startsWith('dsh-'); +} + +/** True when the folder `path` (a directory named `name`) is another operating system's prebuilt binary and can go. */ +export function isOtherOsBinaryFolder(platform, name, path) { + const rule = OTHER_OS[platform] ?? OTHER_OS.linux; + if (isHarnessCodePackage(path)) return false; + return rule.test(name) && NATIVE_FOLDER.test(path); +} + +/** Imports the Windows copy (which works) is also without: browser-side or dev-only bundles, and the document converter the app drops on purpose. */ +const KNOWN_ABSENT = new Set([ + '@deepseek-ai/libreoffice-kit', '@deepseek-ai/dsh-client-ui-dockkit', '@deepseek-ai/dsh-client-web', + '@deepseek-ai/dsh-experimental-webworker-runtime', '@deepseek-ai/dsh-remote-mock', '@deepseek-ai/dsh-client-test-runtime', +]); + +function jsFiles(dir, out = []) { + for (const e of readdirSync(dir, { withFileTypes: true })) { + const p = join(dir, e.name); + if (e.isSymbolicLink()) continue; + if (e.isDirectory()) jsFiles(p, out); + else if (/\.(m?js|cjs)$/.test(e.name)) out.push(p); + } + return out; +} + +/** + * Every bare `@deepseek-ai/` the staged Harness's own packages import (static `from "x"` and `import("x")`) must exist + * in the staged node_modules. Returns the list of `{from, missing}` problems (empty = good). Plugins that are only loaded on + * another platform still count: Node resolves a static import whether or not the code runs. + */ +export function missingHarnessImports(harnessDir) { + const scope = join(harnessDir, 'node_modules', '@deepseek-ai'); + if (!existsSync(scope)) return [{ from: scope, missing: '@deepseek-ai (no installed packages)' }]; + const problems = []; + const seen = new Set(); + const re = /(?:from|import)\s*\(?\s*["'](@deepseek-ai\/[^"'/]+)(?:\/[^"']*)?["']/g; + for (const pkg of readdirSync(scope)) { + const lib = join(scope, pkg, 'lib'); + if (!existsSync(lib)) continue; + for (const file of jsFiles(lib)) { + const text = readFileSync(file, 'utf8'); + for (const m of text.matchAll(re)) { + const name = m[1]; + const key = `${pkg}>${name}`; + if (seen.has(key) || KNOWN_ABSENT.has(name)) continue; + seen.add(key); + if (!existsSync(join(harnessDir, 'node_modules', ...name.split('/'))) + && !existsSync(join(scope, pkg, 'node_modules', ...name.split('/')))) problems.push({ from: `${pkg}`, missing: name }); + } + } + } + return problems; +} diff --git a/apps/desktop/scripts/installed-flow.mjs b/apps/desktop/scripts/installed-flow.mjs new file mode 100644 index 00000000000..7816b5c2460 --- /dev/null +++ b/apps/desktop/scripts/installed-flow.mjs @@ -0,0 +1,310 @@ +#!/usr/bin/env node +/** + * Prove the INSTALLED app layout can start and stop an engine with nothing acquired, using a stub engine. + * + * node apps/desktop/scripts/installed-flow.mjs --install [--work ] [--spy ] + * + * It starts the installed host with the installed node.exe exactly as the Tauri shell does (STRATA_PACKAGED=1, + * STRATA_NO_ACQUIRE=1; Control found beside the host), against a scratch component folder holding a fake engine + * package and a scratch install folder holding one run config. Everything per-user (profiles, runtime state, host data, + * components) lives under --work, so the real profile of whoever runs this is never read or written. + * + * Steps (each one printed, the run exits 1 if any fails): + * host health, Control status (engine usable, acquiring forbidden), models from Control, load through the host + * (profile + `runtime start` under the owner runtime), a chat answer from the stub engine, a second client attaches to + * the same owner/instance, unload stops it, no engine for this PC is a notice with nothing started, the Tauri-style + * clean shutdown stops the engines the host started, a hard-killed host takes its engine with it. + * With --spy the host runs under tests/helpers/acquire-spy.mjs and the run fails on any attempt to reach the internet or + * run an installer. + * + * REAL mode (a test box with a GPU): --components > --models .json + * whose engine is "component:strata-engine"> --model [--backend cuda]. The same host and Control, a real engine and a + * real model: load, a real answer, ownership, unload, the missing-engine notice, load again, clean shutdown. The stub-only + * steps (the marker file, the hard-kill report) are left out. + */ +import { spawn, spawnSync } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, chmodSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]]] : acc), [])); +if (!args.install) { console.error('usage: installed-flow.mjs --install [--work ] [--spy ]'); process.exit(2); } +const install = resolve(args.install); +const isWin = process.platform === 'win32'; +const node = join(install, 'node', isWin ? 'node.exe' : 'node'); +const hostEntry = join(install, 'host', 'server', 'index.mjs'); +const controlDir = join(install, 'control'); +const python = isWin ? join(controlDir, 'python', 'python.exe') : join(controlDir, 'python', 'bin', 'python3'); +const real = !!args.components; +const modelId = String(args.model ?? 'stub'); +const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'strata-installed-flow-'))); +mkdirSync(work, { recursive: true }); +const dirs = { components: real ? resolve(args.components) : join(work, 'components'), models: real ? resolve(args.models) : join(work, 'models'), profiles: join(work, 'profiles'), runtime: join(work, 'runtime'), home: join(work, 'home') }; +// the runtime and profile folders are created by Control itself, with the owner-only ACL it insists on +for (const [name, d] of Object.entries(dirs)) if (!['runtime', 'profiles'].includes(name) && !(real && ['components', 'models'].includes(name))) mkdirSync(d, { recursive: true }); + +const steps = []; +const record = (name, ok, detail = '') => { steps.push({ name, ok: !!ok, detail: String(detail) }); console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + detail : ''}`); }; +const delay = ms => new Promise(r => setTimeout(r, ms)); +const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; +const sha = buf => createHash('sha256').update(buf).digest('hex'); + +// ------------------------------------------------------------------------------ fixtures +const baseEnv = { + ...process.env, + STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, + STRATA_INSTALL_DIR: dirs.models, STRATA_ENGINE_BACKEND: String(args.backend ?? 'cuda'), STRATA_HOME: dirs.home, STRATA_MODELS_DIR: real ? join(work, 'models-unused') : dirs.models, + APPDATA: join(work, 'appdata'), XDG_CONFIG_HOME: join(work, 'xdg'), PYTHONDONTWRITEBYTECODE: '1', +}; +delete baseEnv.STRATA_API_KEY; +mkdirSync(baseEnv.APPDATA, { recursive: true }); +const mark = join(work, 'engine-ran.json'); + +const FAKE_ENGINE = `import os, sys, json +from pathlib import Path +Path(os.environ['FAKE_ENGINE_MARK']).write_text(json.dumps({'pid': os.getpid(), 'script': os.path.abspath(__file__), 'argv': sys.argv[1:]})) +print('READY 4096 stop', flush=True) +for line in sys.stdin: + if line.strip() == 'QUIT': break + if line.startswith(('GEN ', 'BGEN ')): + slot = int(line.split()[1]) if line.startswith('BGEN ') else None + print('T 97', flush=True) + print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True) + if slot is not None: print(f'BADM {slot} 0', flush=True) +`; + +function installFakeEngine() { + const platform = isWin ? 'windows-x86_64' : 'linux-x86_64'; + const folder = join(dirs.components, 'engine', `0.1.45-${platform}-cuda`); + mkdirSync(folder, { recursive: true }); + writeFileSync(join(folder, 'engine_main.py'), FAKE_ENGINE); + const entry = isWin ? 'engine.cmd' : 'engine'; + writeFileSync(join(folder, entry), isWin + ? `@echo off\r\n"${python}" "%~dp0engine_main.py" %*\r\n` + : `#!/bin/sh\nexec "${python}" "$(dirname "$0")/engine_main.py" "$@"\n`); + if (!isWin) chmodSync(join(folder, entry), 0o755); + const files = [entry, 'engine_main.py'].map(p => { const b = readFileSync(join(folder, p)); return { path: p, sha256: sha(b), bytes: b.length }; }); + writeFileSync(join(folder, 'engine-component.json'), JSON.stringify({ schema_version: 1, id: 'strata-engine', version: '0.1.45', platform, backend: 'cuda', entrypoint: entry, files })); + return folder; +} + +function makeTokenizerAndConfig() { + const tok = join(dirs.models, 'tokenizer'); + mkdirSync(tok, { recursive: true }); + const script = `import json, sys\nfrom tools.strata_tokenizer import BYTE_TO_UNICODE\ntok = sys.argv[1]\ntokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ['ab', '<|im_start|>', '<|im_end|>', '<|endoftext|>']\njson.dump({t: i for i, t in enumerate(tokens)}, open(tok + '/vocab.json', 'w'))\nopen(tok + '/merges.txt', 'w').write('a b')\njson.dump([0] * 257 + [3, 3, 3], open(tok + '/token_type.json', 'w'))\n`; + const done = spawnSync(python, ['-c', script, tok], { cwd: controlDir, env: { ...baseEnv, PYTHONNOUSERSITE: '1' }, encoding: 'utf8' }); + if (done.status !== 0) throw new Error('tokenizer fixture failed: ' + done.stderr); + writeFileSync(join(dirs.models, 'strata-stub.json'), JSON.stringify({ exe: 'component:strata-engine', backend: 'cuda', tokenizer: tok, args: [], cwd: work, model_name: 'stub', host: '127.0.0.1', port: 0 })); +} + +const control = (...argv) => spawnSync(python, [join(controlDir, 'strata.py'), ...argv, '--output', 'json'], { cwd: controlDir, env: { ...baseEnv, PYTHONNOUSERSITE: '1', STRATA_NO_ACQUIRE: '1', FAKE_ENGINE_MARK: mark }, encoding: 'utf8', timeout: 120000 }); +const controlJson = (...argv) => { const r = control(...argv); let json = null; try { json = JSON.parse(r.stdout.slice(r.stdout.indexOf('{'))); } catch { /* not json */ } return { code: r.status, json, text: r.stdout + r.stderr }; }; +const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } }; + +// ------------------------------------------------------------------------------ the host +let host = null, port = 0, base = '', spyLog = null, shutdownToken = randomBytes(32).toString('hex'); +async function startHost() { + port = await freePort(); base = `http://127.0.0.1:${port}`; + const hostArgs = [...(args.spy ? ['--import', pathToFileURL(resolve(args.spy)).href] : []), hostEntry]; + if (args.spy) { spyLog = join(work, 'acquire-spy.log'); writeFileSync(spyLog, ''); } + host = spawn(node, hostArgs, { + cwd: join(install, 'host'), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, + env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', + STRATA_NO_ACQUIRE: '1', STRATA_SHUTDOWN_TOKEN: shutdownToken, FAKE_ENGINE_MARK: mark, STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), + ...(spyLog ? { ACQUIRE_SPY_LOG: spyLog } : {}) }, + }); + let log = ''; + host.stdout.on('data', c => { log += c; }); host.stderr.on('data', c => { log += c; }); + host.hostLog = () => log; + for (let i = 0; i < 200; i++) { try { if ((await fetch(base + '/api/health')).ok) return true; } catch { /* not yet */ } await delay(150); } + return false; +} +/** The host started the way the Tauri shell starts it, by a stand-in shell (a node process) that can then be killed hard. */ +async function startHostViaShell() { + port = await freePort(); base = `http://127.0.0.1:${port}`; + const spec = { command: node, args: [hostEntry], options: { + cwd: join(install, 'host'), stdio: 'ignore', windowsHide: true, + env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', + STRATA_NO_ACQUIRE: '1', STRATA_SHUTDOWN_TOKEN: shutdownToken, STRATA_EXIT_WITH_PARENT: '1', FAKE_ENGINE_MARK: mark, + STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } } }; + const shell = spawn(node, ['-e', "const s=JSON.parse(process.env.HOST_SPEC);const c=require('node:child_process').spawn(s.command,s.args,s.options);console.log(c.pid);setInterval(()=>{},1000);"], + { env: { ...process.env, HOST_SPEC: JSON.stringify(spec) }, stdio: ['ignore', 'pipe', 'inherit'], windowsHide: true }); + const hostPid = await new Promise(r => shell.stdout.once('data', c => r(Number(String(c).trim())))); + for (let i = 0; i < 200; i++) { try { if ((await fetch(base + '/api/health')).ok) return { shell, hostPid }; } catch { /* not yet */ } await delay(150); } + return { shell, hostPid, failed: true }; +} +const call = async (path, method = 'GET', body) => { + const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); + return { status: response.status, body: await response.json().catch(() => null) }; +}; +async function waitJob(id, seconds = 120) { + for (let i = 0; i < seconds * 5; i++) { + const state = (await call('/api/native')).body; + const job = state.jobs.find(j => j.id === id); + if (job && job.state !== 'running') return { job, state }; + await delay(200); + } + throw new Error('operation did not finish'); +} +async function stopHost(hard = false) { + if (!host || host.exitCode !== null) return; + if (hard) { if (isWin) spawnSync('taskkill', ['/PID', String(host.pid), '/T', '/F'], { windowsHide: true }); else host.kill('SIGKILL'); } + else host.kill(); + for (let i = 0; i < 100 && host.exitCode === null; i++) await delay(100); +} + +async function main() { + for (const need of [node, hostEntry, python, join(controlDir, 'strata.py')]) if (!existsSync(need)) { record('installed layout', false, `missing ${need}`); return; } + record('installed layout', true, install); + if (real) { + const packages = existsSync(join(dirs.components, 'engine')) ? readdirSync(join(dirs.components, 'engine')) : []; + record('fixtures', packages.length > 0 && existsSync(join(dirs.models, `strata-${modelId}.json`)), `engine package(s) ${packages.join(', ')} in ${dirs.components}; run config strata-${modelId}.json in ${dirs.models}`); + } else { + installFakeEngine(); + makeTokenizerAndConfig(); + record('fixtures', true, `stub engine package in ${dirs.components}; run config strata-stub.json`); + } + + if (!(await startHost())) { record('host healthy', false, host.hostLog().slice(-600)); return; } + record('host healthy', true, base); + + const status = (await call('/api/control/status')).body; + record('Control status: bundled, engine usable, acquiring forbidden', status.control?.python?.startsWith(controlDir) && status.engine?.usable === true && status.acquisition?.forbidden === true, + `python=${status.control?.python}; engine=${status.engine?.engine?.version}; forbidden=${status.acquisition?.forbidden}`); + + const native = (await call('/api/native?refresh=1')).body; + const model = native.installed?.models?.find(m => m.model === modelId); + record('models come from Control', native.available && model?.ready === true && native.packaged === true, `available=${native.available}; model ready=${model?.ready}; ${native.summary ?? native.error}`); + + // ---- load + const started = (await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body; + const loaded = await waitJob(started.id, 400); + const instance = loaded.state.instances[0]; + record('load through the host starts the engine under Control', loaded.job.state === 'done' && instance?.status === 'ready', `job=${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}`); + let ran = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; + if (real) { + const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); + ran = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]), script: listed[0].trim().split(/\s+/)[1] } : null; + record('the engine process running is the binary from the component folder', !!ran, listed[0] ? listed[0].trim().slice(0, 160) : 'no engine process under the component folder'); + } else { + record('the engine that ran is the one in the component folder', ran && ran.script.toLowerCase().startsWith(dirs.components.toLowerCase()), ran?.script ?? 'engine never ran'); + } + + const runtime = controlJson('runtime', 'status', '--profile', 'app-1'); + record('a second client sees the same owner and instance (ownership)', runtime.json?.state === 'ready' && !!runtime.json.owner_id && !!runtime.json.instance_id && runtime.json.host_pid !== host.pid, + `state=${runtime.json?.state}; owner=${String(runtime.json?.owner_id).slice(0, 8)}; instance=${String(runtime.json?.instance_id).slice(0, 8)}; owner host pid ${runtime.json?.host_pid} is not the app host (${host.pid})`); + + // ---- answer + const chat = await call('/v1/chat/completions', 'POST', real + ? { model: instance?.apiModelId ?? modelId, messages: [{ role: 'user', content: 'Reply with exactly one word: pong' }], max_tokens: 200, temperature: 0, reasoning_effort: 'none', stream: false } + : { model: instance?.apiModelId ?? modelId, messages: [{ role: 'user', content: 'hi' }], max_tokens: 4, stream: false }); + const message = chat.body?.choices?.[0]?.message ?? {}; + const answer = `${message.content ?? ''}${message.reasoning_content ?? ''}`; // the stub emits token 97 ("a"); the server files it as reasoning + record(real ? 'the real model answers through the host (the answer text is checked)' : 'the engine answers through the host (the stub token, not an error)', + chat.status === 200 && (real ? /pong/i.test(answer) : answer === 'a'), `status=${chat.status}; answer=${JSON.stringify(answer.slice(0, 200))}${chat.status === 200 ? '' : ' ' + JSON.stringify(chat.body).slice(0, 160)}`); + + // ---- unload + const unloaded = await call(`/api/native/instances/${instance.id}/unload`, 'POST', {}); + await delay(500); + const after = controlJson('runtime', 'status', '--profile', 'app-1'); + for (let i = 0; i < 100 && ran && alive(ran.pid); i++) await delay(100); // a real engine takes a moment to release the GPU + record('unload stops the engine', unloaded.status === 200 && after.json?.state === 'stopped' && (!ran || !alive(ran.pid)), `status=${unloaded.status}; runtime=${after.json?.state}; engine pid ${ran?.pid} alive=${ran ? alive(ran.pid) : 'n/a'}`); + + // ---- no engine for this PC + const hidden = join(dirs.components, real ? 'engine.hidden-by-flow' : 'engine.gone'); + renameSync(join(dirs.components, 'engine'), hidden); + rmSync(mark, { force: true }); + const missing = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id); + record('no engine for this PC is a notice and nothing is started', missing.job.state === 'error' && /No engine for this PC/.test(missing.job.error) && /never downloads/.test(missing.job.error) && !existsSync(mark), + `${missing.job.state}: ${String(missing.job.error).slice(0, 160)}`); + const refused = await waitJob((await call('/api/native/operations', 'POST', { kind: 'install', args: { family: 'qwen', model: 'IQ2_XS' } })).body.id); + record('installing from the app is refused (Terminal only)', refused.job.state === 'error' && /Terminal/.test(refused.job.error), refused.job.error); + const binary = await call('/api/engine/binary', 'POST'); + record('the llama.cpp download route is refused', binary.status === 409 && /never downloads/.test(binary.body?.error ?? ''), `${binary.status} ${binary.body?.error}`); + + // ---- clean shutdown (what the Tauri shell does on exit) + renameSync(hidden, join(dirs.components, 'engine')); + rmSync(mark, { force: true }); + const again = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400); + let ran2 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; + if (real) { + const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); + ran2 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null; + } + record('load again after the engine package returns', again.job.state === 'done', again.job.error ?? ''); + const wrong = await fetch(base + '/api/control/shutdown', { method: 'POST', headers: { 'x-strata-shutdown': 'nope' } }); + record('shutdown without the shell\'s secret is refused', wrong.status === 403, String(wrong.status)); + const exited = new Promise(r => host.once('exit', code => r(code))); + const stopping = await fetch(base + '/api/control/shutdown', { method: 'POST', headers: { 'x-strata-shutdown': shutdownToken } }); + const code = await Promise.race([exited, delay(90000).then(() => 'timeout')]); + for (let i = 0; i < 100 && ran2 && alive(ran2.pid); i++) await delay(100); + const final = controlJson('runtime', 'status', '--profile', 'app-1'); + record('clean shutdown stops the engine the app started and exits', stopping.status === 202 && code === 0 && final.json?.state === 'stopped' && (!ran2 || !alive(ran2.pid)), `status=${stopping.status}; host exit=${code}; runtime=${final.json?.state}; engine alive=${ran2 ? alive(ran2.pid) : 'n/a'}`); + + // ---- hard kill: an engine whose app host dies ends with it (the owner follows the host: runtime start --die-with-pid) + if (!(await startHost())) { record('host restarts', false, host.hostLog().slice(-400)); return; } + await call('/api/native?refresh=1'); + rmSync(mark, { force: true }); + const third = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400); + let ran3 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; + if (real) { + const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); + ran3 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null; + record('(real) the engine is up before the host is killed', !!ran3, listed[0] ? listed[0].trim().slice(0, 120) : 'no engine process'); + } + await stopHost(true); + for (let i = 0; i < 600 && ran3 && alive(ran3.pid); i++) await delay(100); // the owner notices within a second, drains, stops + const orphan = controlJson('runtime', 'status', '--profile', 'app-1'); + record('a hard-killed app host takes its engine with it', third.job.state === 'done' && (!ran3 || !alive(ran3.pid)), `engine alive=${ran3 ? alive(ran3.pid) : 'n/a'}; runtime=${orphan.json?.state ?? orphan.json?.error?.message}`); + const cleanup = controlJson('runtime', 'stop', '--profile', 'app-1'); + record('nothing is left to stop afterwards', /stopped|not managed/.test(JSON.stringify(cleanup.json)) && controlJson('runtime', 'status', '--profile', 'app-1').json?.state === 'stopped', JSON.stringify(cleanup.json).slice(0, 160)); + + // ---- the shell itself is killed (what the desktop shell's crash or kill looks like to the host): the host leaves, and + // its engine with it, with nothing announced. Windows also has the job object; this is the path that works everywhere. + const started2 = await startHostViaShell(); + if (started2.failed) { record('host starts under a stand-in shell', false, ''); try { started2.shell.kill('SIGKILL'); } catch { /* gone */ } } + else { + await call('/api/native?refresh=1'); + rmSync(mark, { force: true }); + const fourth = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400); + let ran4 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; + if (real) { + const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); + ran4 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null; + } + if (isWin) spawnSync('taskkill', ['/PID', String(started2.shell.pid), '/F'], { windowsHide: true }); else started2.shell.kill('SIGKILL'); + for (let i = 0; i < 100 && alive(started2.hostPid); i++) await delay(100); + const hostGone = !alive(started2.hostPid); + for (let i = 0; i < 900 && ran4 && alive(ran4.pid); i++) await delay(100); + const engineGone = !ran4 || !alive(ran4.pid); + record('a killed shell takes the host and its engine with it', fourth.job.state === 'done' && hostGone && engineGone, + `host pid ${started2.hostPid} gone=${hostGone}; engine pid ${ran4?.pid} gone=${engineGone}; runtime=${controlJson('runtime', 'status', '--profile', 'app-1').json?.state}`); + controlJson('runtime', 'stop', '--profile', 'app-1'); + } + + await finishSpy(); +} + +async function finishSpy() { + if (spyLog) { + const attempts = readFileSync(spyLog, 'utf8').split('\n').filter(Boolean); + record('no acquisition attempt by the host during the whole run (spy)', attempts.length === 0, attempts.join(' | ')); + } +} + +try { await main(); } +catch (error) { record('flow', false, error.stack ?? error.message); } +finally { + try { const hid = join(dirs.components, 'engine.hidden-by-flow'); if (real && existsSync(hid) && !existsSync(join(dirs.components, 'engine'))) renameSync(hid, join(dirs.components, 'engine')); } catch { /* reported by the run */ } + await stopHost(true); + controlJson('runtime', 'stop', '--profile', 'app-1'); + controlJson('runtime', 'stop', '--profile', 'app-2'); +} +const failed = steps.filter(s => !s.ok); +writeFileSync(join(work, 'installed-flow.json'), JSON.stringify({ ok: failed.length === 0, install, work, steps }, null, 1)); +console.log(`\n${steps.length - failed.length}/${steps.length} ok; report ${join(work, 'installed-flow.json')}`); +if (!args.keep && !args.work && failed.length === 0) { try { rmSync(work, { recursive: true, force: true }); } catch { /* leave it */ } } +process.exit(failed.length ? 1 : 0); diff --git a/apps/desktop/scripts/installer-mockups.mjs b/apps/desktop/scripts/installer-mockups.mjs new file mode 100644 index 00000000000..cc7a3c8f22a --- /dev/null +++ b/apps/desktop/scripts/installer-mockups.mjs @@ -0,0 +1,73 @@ +#!/usr/bin/env node +/** + * Mock-ups of the Windows installer in Strata's own look: four screens (welcome, where, installing, done), light and dark, drawn with + * the app's built CSS (apps/host/dist) and brand files, then photographed with Chrome. Nothing here is built or shipped: it is what + * the owner is shown before an installer is chosen. + * + * node apps/desktop/scripts/installer-mockups.mjs [--out ] + */ +import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const host = resolve(here, '../../host'); +const out = resolve(args.out ?? join(here, '../installer-mockups')); +mkdirSync(out, { recursive: true }); +const dist = join(host, 'dist'); +const css = readdirSync(join(dist, 'assets')).filter(f => f.endsWith('.css')).map(f => readFileSync(join(dist, 'assets', f), 'utf8')).join('\n'); +const logo = theme => readFileSync(join(dist, 'brand', `strata-lockup-${theme}.svg`), 'utf8'); +const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); + +const check = ''; +const folder = ''; + +const screens = { + welcome: theme => `
+

State of the art. At home.

Strata runs AI on your own computer.
Setting it up takes a few minutes.

+
${check}Private${check}Fast${check}Easy to use
+
Installs for you only. No administrator needed.
`, + where: theme => `
+

Where should Strata go?

This is the right place for most people.

+
${folder}
Your Strata folderC:\\Users\\Alex\\AppData\\Local\\Strata
+

About 310 MB. Your models and chats are kept somewhere else and are never removed by an update.

+
`, + installing: theme => `
+

Installing Strata…

Copying the app and its engine room. You can keep working meanwhile.

+
+
62% · 190 / 310 MB
About 1 min left
+
Next: choose your first model inside Strata.
`, + done: theme => `
+

Strata is ready.

Open it to pick your first model. Strata downloads it for you and gets it ready.

+
A shortcut was added to your Start menu and desktop.
`, +}; + +const page = (name, theme) => `
Strata setup– ☐ ✕
+
${screens[name](theme)}
`; + +const browser = await chromium.launch({ executablePath: CHROME, headless: true }); +const written = []; +for (const theme of ['light', 'dark']) { + for (const name of Object.keys(screens)) { + const tab = await browser.newPage({ viewport: { width: 860, height: 620 }, deviceScaleFactor: 1 }); + await tab.setContent(page(name, theme)); + await tab.waitForTimeout(250); + const file = join(out, `${name}-${theme}.png`); + await tab.screenshot({ path: file }); + written.push(file); + await tab.close(); + } +} +await browser.close(); +console.log(written.join('\n')); diff --git a/apps/desktop/scripts/local-gguf-e2e.mjs b/apps/desktop/scripts/local-gguf-e2e.mjs new file mode 100644 index 00000000000..32e49fa77b0 --- /dev/null +++ b/apps/desktop/scripts/local-gguf-e2e.mjs @@ -0,0 +1,126 @@ +#!/usr/bin/env node +/** + * "Use your own GGUF" end to end on a box, through the installed app layout (packaged host + bundled Control + a real engine component): + * preview a folder of a supported model, preview an unsupported GGUF (must be refused in plain terms), prepare the supported one + * (pack, from the folder, nothing copied), load it, get a chat answer, unload, shut down, and check nothing is left running. + * + * node local-gguf-e2e.mjs --root /data/ui4-e2e --good /data/141-gyro/models/IQ2_XS --bad /data/ui4-e2e/bad [--context 8192] [--backend cuda|metal] + * (the app folder is /app: node/, host/, control/ ...; /components gets the engine, from /app/engine-bundle when the app carries one) + */ +import { spawn, spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { join, resolve } from 'node:path'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const root = resolve(args.root); +const good = args.good, bad = args.bad; +const context = Number(args.context ?? 8192); +const app = join(root, 'app'); +const dirs = { components: join(root, 'components'), install: join(root, 'install'), profiles: join(root, 'profiles'), runtime: join(root, 'runtime'), home: join(root, 'home'), xdg: join(root, 'xdg'), appdata: join(root, 'appdata') }; +for (const d of [dirs.install, dirs.home, dirs.xdg, dirs.appdata]) mkdirSync(d, { recursive: true }); +const delay = ms => new Promise(r => setTimeout(r, ms)); +const steps = []; +let failed = false; +const record = (name, ok, detail = '') => { steps.push({ name, ok: !!ok, detail: String(detail).slice(0, 400) }); console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + String(detail).slice(0, 300) : ''}`); if (!ok) failed = true; }; +const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; + +const env = { ...process.env, STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_INSTALL_DIR: dirs.install, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(root, 'Strata-data'), STRATA_ENGINE_BACKEND: args.backend ?? 'cuda', XDG_CONFIG_HOME: dirs.xdg, APPDATA: dirs.appdata, PYTHONDONTWRITEBYTECODE: '1' }; +delete env.STRATA_API_KEY; +const port = await freePort(); +const base = `http://127.0.0.1:${port}`; +const host = spawn(join(app, 'node', 'node'), [join(app, 'host', 'server', 'index.mjs')], { cwd: join(app, 'host'), stdio: ['ignore', 'pipe', 'pipe'], detached: false, + env: { ...env, STRATA_PORT: String(port), STRATA_DIST: join(app, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', STRATA_EXIT_WITH_PARENT: '1', + STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_WORKSPACE: join(root, 'workspace') } }); +mkdirSync(join(root, 'workspace'), { recursive: true }); +let hostLog = ''; host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; }); +const call = async (path, method = 'GET', body) => { const r = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); return { status: r.status, body: await r.json().catch(() => null) }; }; +async function waitJob(id, seconds) { + const until = Date.now() + seconds * 1000; + let last = ''; + while (Date.now() < until) { + const state = (await call('/api/native')).body; + const job = state.jobs.find(j => j.id === id); + if (job && job.state !== 'running') return { job, state }; + if (job && job.summary !== last) { last = job.summary; console.log(' ...', String(job.summary).slice(0, 140)); } + await delay(2000); + } + throw new Error('operation did not finish in time'); +} +const engineProcs = () => spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(join(dirs.components, 'engine')) && /\/strata( |$)/.test(l)); + +async function main() { + let up = false; + for (let i = 0; i < 200 && !up; i++) { try { up = (await fetch(base + '/api/health')).ok; } catch { await delay(150); } } + record('host healthy', up, up ? base : hostLog.slice(-500)); + if (!up) return; + let status = (await call('/api/control/status')).body; + for (let i = 0; i < 180 && status?.engineSetup; i++) { await delay(1000); status = (await call('/api/control/status')).body; } // the engine that came with the app is copied on the first start + record('Control status: bundled, engine usable', status?.engine?.usable === true, `engine=${status?.engine?.engine?.version} ${status?.engine?.notice ?? ''}`); + await call('/api/native?refresh=1'); + + // ---- the unsupported GGUF: a plain refusal + const badPreview = await call('/api/native/local/preview', 'POST', { path: bad }); + const badIssues = badPreview.body?.preview?.issues ?? badPreview.body?.issues ?? []; + const badStatus = badPreview.body?.preview?.file_set_status; + console.log(' bad preview:', badPreview.status, JSON.stringify(badPreview.body).slice(0, 400)); + record('an unsupported GGUF is refused, nothing adopted', badPreview.status === 200 ? (badStatus !== 'plausible' || !badPreview.body.preview.candidate_selection) : badPreview.status >= 400, `status=${badPreview.status}; file_set_status=${badStatus}; issues=${JSON.stringify(badIssues)}`); + + // ---- the supported folder + const goodPreview = await call('/api/native/local/preview', 'POST', { path: good }); + const selection = goodPreview.body?.preview?.candidate_selection; + console.log(' good preview:', JSON.stringify(goodPreview.body).slice(0, 500)); + record('a folder of a supported model is recognised', goodPreview.status === 200 && goodPreview.body?.preview?.file_set_status === 'plausible' && !!selection, `family=${selection?.family}; model=${selection?.model}; files=${goodPreview.body?.preview?.file_count}`); + if (!selection || args.only === 'preview') return; + + // ---- prepare (what the page's button does): install from the folder, nothing copied or downloaded + const native0 = (await call('/api/native?refresh=1')).body; + const catalogSize = native0.catalog?.families?.find(f => f.family === selection.family)?.sizes.find(s => s.model === selection.model); + record('the catalog lists the recognised version', !!catalogSize, catalogSize ? `id=${catalogSize.id}` : `no ${selection.family}/${selection.model} in the catalog`); + const started = await call('/api/native/operations', 'POST', { kind: 'install', args: { family: selection.family, model: selection.model, gguf_dir: good, context, vision: 'no' } }); + record('prepare starts', started.status < 300 && !!started.body?.id, `status=${started.status} ${JSON.stringify(started.body).slice(0, 200)}`); + if (!started.body?.id) return; + const prepared = await waitJob(started.body.id, 3600); + record('prepare finishes', prepared.job.state === 'done', `${prepared.job.state}: ${prepared.job.error ?? prepared.job.summary}`); + if (prepared.job.state !== 'done') return; + const native1 = (await call('/api/native?refresh=1')).body; + const modelId = catalogSize?.id ?? `${selection.family === 'qwen' ? '' : selection.family + '-'}${String(selection.model).toLowerCase()}`; + const entry = native1.installed?.models?.find(m => m.model === modelId); + record('the model is ready and points at the folder, not a copy', entry?.ready === true, `model=${modelId}; ready=${entry?.ready}; dataFolder=${entry?.dataFolder}`); + if (!entry?.ready) return; + + // ---- load + const load = await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } }); + const loaded = await waitJob(load.body.id, 1800); + const instance = loaded.state.instances[0]; + record('load starts the engine from the component folder', loaded.job.state === 'done' && instance?.status === 'ready', `job=${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}`); + if (instance?.status !== 'ready') return; + record('one engine process is running', engineProcs().length === 1, engineProcs().map(l => l.trim().slice(0, 140)).join(' | ')); + + // ---- a chat answer, checked + const chat = await fetch(base + '/api/chat/stream', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sessionId: 'e2e-chat', message: 'Reply with exactly one word: pong', history: [], nativeModelId: instance.id, thinking: 'Off', agent: false, workspaceId: null }) }); + let text = '', done = null; + for await (const chunk of chat.body) { + for (const line of Buffer.from(chunk).toString('utf8').split('\n')) { + if (!line.trim()) continue; + try { const f = JSON.parse(line); if (f.type === 'delta') text += f.text ?? ''; if (f.type === 'done') done = f; if (f.type === 'error') text += ` [error: ${f.message}]`; } catch { /* partial line */ } + } + } + record('the model answers through the app (the answer text is checked)', chat.status === 200 && /pong/i.test(text), `status=${chat.status}; answer=${JSON.stringify(text.slice(0, 120))}; tokensOut=${done?.tokensOut}; tps=${done?.tps}`); + + // ---- unload, shutdown, nothing left + const unload = await call(`/api/native/instances/${instance.id}/unload`, 'POST'); + await delay(3000); + record('unload stops the engine', unload.status < 300 && engineProcs().length === 0, `status=${unload.status}; engines left=${engineProcs().length}`); +} + +try { await main(); } catch (e) { record('the flow', false, e?.stack ?? e); } +host.kill(); +for (let i = 0; i < 100 && host.exitCode === null; i++) await delay(100); +if (host.exitCode === null) host.kill('SIGKILL'); +await delay(2000); +const left = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => (l.includes(dirs.install) || l.includes(join(app, 'host'))) && !l.includes('ps -eo')); +record('nothing of this run is left running', left.length === 0, left.join(' | ').slice(0, 300)); +writeFileSync(join(root, 'e2e-result.json'), JSON.stringify({ steps, hostLogTail: hostLog.slice(-2000) }, null, 1)); +console.log(failed ? 'FAILED' : 'ALL OK'); +process.exit(failed ? 1 : 0); diff --git a/apps/desktop/scripts/make-dmg.sh b/apps/desktop/scripts/make-dmg.sh new file mode 100755 index 00000000000..909579f8773 --- /dev/null +++ b/apps/desktop/scripts/make-dmg.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Build the Strata DMG without a Finder session. +# +# Tauri's default DMG step runs an AppleScript that asks Finder to arrange the window (icon +# positions, background). Finder AppleEvents time out in a non-GUI or sandboxed context — observed +# here as `Finder got an error: AppleEvent timed out. (-1712)` — so the default path cannot be +# relied on for an automated build. The upstream `create-dmg` script already supports exactly this +# case via `--skip-jenkins`, which produces a plain, correct DMG with the app and the Applications +# drop link and no cosmetic arrangement. +# +# Usage: scripts/make-dmg.sh [output.dmg] +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DESKTOP="$(cd "$HERE/.." && pwd)" +BUNDLE="$DESKTOP/src-tauri/target/release/bundle" +APP="$BUNDLE/macos/Strata.app" +VERSION="$(grep -m1 '^version = ' "$DESKTOP/src-tauri/Cargo.toml" | cut -d'"' -f2)" # the one place the app version is written +OUT="${1:-$BUNDLE/dmg/Strata_${VERSION}_aarch64.dmg}" + +if [ ! -d "$APP" ]; then + echo "error: $APP does not exist; run 'cargo tauri build --bundles app' first" >&2 + exit 1 +fi + +WORK="$(mktemp -d -t strata-dmg)" +trap 'rm -rf "$WORK"' EXIT + +# A staging folder is what create-dmg copies into the image: the app, and nothing else. +# +# The Applications drop link is created by `--app-drop-link` below. Adding one here as well makes +# create-dmg fail with "File exists", because it links into the volume it is assembling. +mkdir -p "$WORK/stage" +cp -R "$APP" "$WORK/stage/" + +# Reuse Tauri's vendored create-dmg if the bundler left it behind, otherwise take it from the +# bundle cache. Building it yourself is not necessary and not expected. +SCRIPT="$BUNDLE/dmg/bundle_dmg.sh" +if [ ! -x "$SCRIPT" ]; then + echo "error: $SCRIPT not found; run 'cargo tauri build --bundles dmg' once to vendor it" >&2 + exit 1 +fi + +mkdir -p "$(dirname "$OUT")" +rm -f "$OUT" + +# --skip-jenkins: no Finder AppleScript. Everything else is the same code path Tauri uses. +"$SCRIPT" \ + --volname "Strata $VERSION" \ + --volicon "$BUNDLE/macos/Strata.app/Contents/Resources/Strata.icns" \ + --app-drop-link 400 200 \ + --skip-jenkins \ + --no-internet-enable \ + "$OUT" "$WORK/stage" + +echo +echo "built: $OUT" +ls -lh "$OUT" | awk '{print "size: " $5}' +shasum -a 256 "$OUT" diff --git a/apps/desktop/scripts/make-icons.mjs b/apps/desktop/scripts/make-icons.mjs new file mode 100644 index 00000000000..411e4b97b31 --- /dev/null +++ b/apps/desktop/scripts/make-icons.mjs @@ -0,0 +1,78 @@ +#!/usr/bin/env node +/** + * The app and installer icon, refined from the existing Strata mark (apps/host/public/brand/strata-mark-*.svg and the current + * icons/icon.png): the same three rounded bars on the same dark tile, in the same colours. Nothing is redrawn. What changes is + * how it is cut for small sizes: at 16-48 px the bars are snapped to whole pixels and made a little bolder and wider so they + * stay crisp instead of blurring; from 64 px up the geometry is the mark's own proportions. + * + * node apps/desktop/scripts/make-icons.mjs [--out ] writes icon-.png for every size and icon.ico + */ +import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const host = resolve(here, '../../host'); +const out = resolve(args.out ?? join(here, '../src-tauri/icons')); +mkdirSync(out, { recursive: true }); +const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); + +const TILE = '#161a1d', LIGHT = '#eef1f3', GREEN = '#34d399'; // the colours of the current icon.png + +/** Integer geometry for the small sizes: bars on whole pixels, centred. Returns [{x,y,w,h,fill}]. */ +function hinted(size) { + const bar = Math.max(2, Math.round(size * 0.14)), gap = Math.max(2, Math.round(size * 0.1)), mid = bar + 1; + const total = 2 * bar + mid + 2 * gap, top = Math.floor((size - total) / 2); + const even = w => (w % 2 === size % 2 ? w : w + 1); + const wide = even(Math.round(size * 0.5)), long = even(Math.round(size * 0.76)); + return [ + { x: (size - wide) / 2, y: top, w: wide, h: bar, fill: LIGHT }, + { x: (size - long) / 2, y: top + bar + gap, w: long, h: mid, fill: GREEN }, + { x: (size - wide) / 2, y: top + bar + gap + mid + gap, w: wide, h: bar, fill: LIGHT }, + ]; +} +/** The mark's own proportions (from icon.png at 512): bars 34% / 50% / 34% wide, 9% high, on a tile with 21.5% corners. */ +function proportional(size) { + const k = size / 512; + return [ + { x: 170 * k, y: 156 * k, w: 173 * k, h: 46 * k, fill: LIGHT }, + { x: 128 * k, y: 232 * k, w: 256 * k, h: 48 * k, fill: GREEN }, + { x: 170 * k, y: 309 * k, w: 173 * k, h: 46 * k, fill: LIGHT }, + ]; +} +function svg(size) { + const small = size <= 48; + const bars = (small ? hinted(size) : proportional(size)); + const radius = small ? Math.round(size * 0.22) : size * 0.215; + const rects = bars.map(b => ``).join(''); + return `${rects}`; +} + +const SIZES = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256, 512, 1024]; +const browser = await chromium.launch({ executablePath: CHROME, headless: true }); +const png = {}; +for (const size of SIZES) { + const page = await browser.newPage({ viewport: { width: size, height: size }, deviceScaleFactor: 1 }); + await page.setContent(`${svg(size)}`); + png[size] = await page.screenshot({ omitBackground: true, clip: { x: 0, y: 0, width: size, height: size } }); + await page.close(); + writeFileSync(join(out, `icon-${size}.png`), png[size]); +} +await browser.close(); + +// The .ico: one PNG image per size (16-256), the sizes Windows asks for at 100-250% scaling. +const ICO = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256]; +const head = Buffer.alloc(6); head.writeUInt16LE(0, 0); head.writeUInt16LE(1, 2); head.writeUInt16LE(ICO.length, 4); +let offset = 6 + 16 * ICO.length; +const entries = [], blobs = []; +for (const size of ICO) { + const data = png[size], e = Buffer.alloc(16); + e.writeUInt8(size === 256 ? 0 : size, 0); e.writeUInt8(size === 256 ? 0 : size, 1); e.writeUInt8(0, 2); e.writeUInt8(0, 3); + e.writeUInt16LE(1, 4); e.writeUInt16LE(32, 6); e.writeUInt32LE(data.length, 8); e.writeUInt32LE(offset, 12); + offset += data.length; entries.push(e); blobs.push(data); +} +writeFileSync(join(out, 'icon.ico'), Buffer.concat([head, ...entries, ...blobs])); +writeFileSync(join(out, 'icon.png'), png[512]); +console.log('icons in', out, ICO.join(',')); diff --git a/apps/desktop/scripts/make-installer-images.mjs b/apps/desktop/scripts/make-installer-images.mjs new file mode 100644 index 00000000000..f12d6cc152a --- /dev/null +++ b/apps/desktop/scripts/make-installer-images.mjs @@ -0,0 +1,66 @@ +#!/usr/bin/env node +/** + * The installer's pictures, drawn from the app's own design: the light surface and ink colours of the app (src/styles tokens), the + * brand lockup and mark files, GT Walsheim Bold for the words (baked into the pictures, because NSIS cannot use a web font). + * + * node apps/desktop/scripts/make-installer-images.mjs [--out ] [--preview ] + * + * Writes sidebar.bmp (164x314, the welcome and finish pages) and header.bmp (150x57, the other pages) as 24-bit BMPs, and with + * --preview the same as PNGs at 3x. + */ +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { tmpdir } from 'node:os'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const host = resolve(here, '../../host'); +const out = resolve(args.out ?? join(here, '../src-tauri/nsis')); +mkdirSync(out, { recursive: true }); +const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); +const font = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Bold.woff2')).href; +const fontMedium = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Medium.woff2')).href; +const lockup = readFileSync(join(host, 'public/brand/strata-lockup-light.svg'), 'utf8'); +const mark = readFileSync(join(host, 'public/brand/strata-mark-light.svg'), 'utf8'); + +// the app's light tokens +const SURFACE = '#f9fafb', INK = '#171b1e', MUTED = '#5b646b', ACCENT = '#10b981', LINE = '#e3e8ea'; +const css = `@font-face{font-family:GT;font-weight:700;src:url(${font})}@font-face{font-family:GT;font-weight:500;src:url(${fontMedium})} +*{box-sizing:border-box}body{margin:0;font-family:GT,'Segoe UI',sans-serif;color:${INK};background:${SURFACE}}`; + +const pages = { + sidebar: { w: 164, h: 314, html: `
+
${lockup.replace(' +
+
State of
the art.
At home.
+
AI on your own computer.
Private. Fast. Easy.
+
+
` }, + header: { w: 150, h: 57, html: `
${lockup.replace('` }, +}; + +const browser = await chromium.launch({ executablePath: CHROME, headless: true }); +const work = join(tmpdir(), 'strata-installer-images'); mkdirSync(work, { recursive: true }); +for (const [name, page] of Object.entries(pages)) { + for (const scale of [1, 3]) { + const file = join(work, `${name}.html`); + writeFileSync(file, `${page.html}`); + const tab = await browser.newPage({ viewport: { width: page.w, height: page.h }, deviceScaleFactor: scale }); + await tab.goto(pathToFileURL(file).href); + await tab.evaluate(() => document.fonts.ready); + await tab.waitForTimeout(200); + const png = join(work, `${name}@${scale}.png`); + await tab.screenshot({ path: png, clip: { x: 0, y: 0, width: page.w, height: page.h } }); + await tab.close(); + if (scale === 3 && args.preview) { mkdirSync(resolve(args.preview), { recursive: true }); writeFileSync(join(resolve(args.preview), `${name}.png`), readFileSync(png)); } + } +} +await browser.close(); +// 24-bit BMP, the format NSIS wants: render at 3x, shrink with a good filter +const py = `import sys\nfrom PIL import Image\nfor name in ('sidebar','header'):\n im = Image.open(sys.argv[1] + '/' + name + '@3.png').convert('RGB')\n w, h = im.width // 3, im.height // 3\n im.resize((w, h), Image.LANCZOS).save(sys.argv[2] + '/' + name + '.bmp', 'BMP')\n`; +const done = spawnSync('python', ['-c', py, work, out], { encoding: 'utf8' }); +if (done.status !== 0) { console.error(done.stderr); process.exit(1); } +console.log('wrote', join(out, 'sidebar.bmp'), join(out, 'header.bmp')); diff --git a/apps/desktop/scripts/make-tester-readme.sh b/apps/desktop/scripts/make-tester-readme.sh new file mode 100644 index 00000000000..e38103c8073 --- /dev/null +++ b/apps/desktop/scripts/make-tester-readme.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Write a tester's README with the checksums and sizes of the files it names, computed from the files themselves. +# +# apps/desktop/scripts/make-tester-readme.sh