scientific-computing-system 1.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +284 -0
- package/LICENSE +0 -0
- package/README.md +89 -218
- package/SECURITY.md +0 -0
- package/bin/scs.js +12 -2
- package/index.js +115 -1
- package/package.json +45 -1
- package/.binder/postBuild +0 -9
- package/.binder/requirements.txt +0 -10
- package/.gitattributes +0 -35
- package/.github/CODEOWNERS +0 -4
- package/.github/FUNDING.yml +0 -3
- package/.github/ISSUE_TEMPLATE/bug_report.md +0 -50
- package/.github/ISSUE_TEMPLATE/config.yml +0 -8
- package/.github/ISSUE_TEMPLATE/feature_request.md +0 -28
- package/.github/PULL_REQUEST_TEMPLATE.md +0 -29
- package/.github/dependabot.yml +0 -32
- package/.github/labeler.yml +0 -50
- package/.github/workflows/benchmarks.yml +0 -97
- package/.github/workflows/bot-reviewer.yml +0 -58
- package/.github/workflows/changelog.yml +0 -130
- package/.github/workflows/cli-package-smoke.yml +0 -45
- package/.github/workflows/codeql.yml +0 -55
- package/.github/workflows/npm-publish.yml +0 -33
- package/.github/workflows/p08-cancel-noncanonical-runs.yml +0 -41
- package/.github/workflows/pr-automation.yml +0 -78
- package/.github/workflows/public-external-validation-p08-v2-glm.yml +0 -161
- package/.github/workflows/public-external-validation-p08-v2-recovery-merge-gate.yml +0 -72
- package/.github/workflows/public-external-validation-p08-v2-recovery-merge.yml +0 -113
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-anatomy-gate.yml +0 -57
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge-gate.yml +0 -63
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge.yml +0 -89
- package/.github/workflows/public-external-validation-p08-v2-run-recovery.yml +0 -182
- package/.github/workflows/public-external-validation-p08-v3-glm-gate.yml +0 -67
- package/.github/workflows/public-external-validation-p08-v4-recovery-glm-gate.yml +0 -78
- package/.github/workflows/public-external-validation-p08-v4-recovery-glm.yml +0 -248
- package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm-gate.yml +0 -66
- package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm.yml +0 -218
- package/.github/workflows/pypi-registry-smoke.yml +0 -116
- package/.github/workflows/release.yml +0 -359
- package/.github/workflows/tests.yml +0 -250
- package/.github/workflows/tmp-compassion-raw-acquire.yml +0 -63
- package/.github/workflows/wsl-science-runner-smoke.yml +0 -45
- package/.pre-commit-config.yaml +0 -48
- package/CITATION.cff +0 -29
- package/CODE_OF_CONDUCT.md +0 -25
- package/CONTRIBUTING.md +0 -275
- package/ROADMAP.md +0 -155
- package/assets/logo.svg +0 -38
- package/assets/social_preview.png +0 -0
- package/benchmarks/results.json +0 -43
- package/benchmarks/robust_runner.py +0 -118
- package/benchmarks/run_benchmarks.py +0 -394
- package/cliff.toml +0 -100
- package/dashboard/app.py +0 -224
- package/docs/ARCHITECTURE.md +0 -252
- package/docs/CASE_STUDY_HUBBLE.md +0 -78
- package/docs/CASE_STUDY_QUANTUM_ML.md +0 -79
- package/docs/api.md +0 -133
- package/docs/assets/icon.svg +0 -17
- package/docs/assets/logo.svg +0 -38
- package/docs/benchmarks.md +0 -62
- package/docs/cookbook.md +0 -930
- package/docs/getting-started.md +0 -185
- package/docs/index.md +0 -111
- package/docs/maintenance.md +0 -61
- package/docs/ml_reference.md +0 -92
- package/docs/research-workflows.md +0 -82
- package/docs/stylesheets/extra.css +0 -122
- package/docs/tour_of_numerical_methods.md +0 -330
- package/docs/tutorials/core_demo.md +0 -35
- package/docs/tutorials/data_analysis_demo.md +0 -43
- package/docs/tutorials/diffeq_demo.md +0 -48
- package/docs/tutorials/fft2_demo.md +0 -67
- package/docs/tutorials/graph_demo.md +0 -45
- package/docs/tutorials/hypothesis_demo.md +0 -44
- package/docs/tutorials/hypothesis_tests_demo.md +0 -170
- package/docs/tutorials/hypothesis_with_stats_demo.md +0 -80
- package/docs/tutorials/knowledge_demo.md +0 -114
- package/docs/tutorials/linalg_demo.md +0 -103
- package/docs/tutorials/math_utils_demo.md +0 -46
- package/docs/tutorials/ml_advanced_demo.md +0 -96
- package/docs/tutorials/ml_and_viz_demo.md +0 -93
- package/docs/tutorials/ml_demo.md +0 -70
- package/docs/tutorials/modeling_demo.md +0 -82
- package/docs/tutorials/montecarlo_demo.md +0 -42
- package/docs/tutorials/nlp_attention_demo.md +0 -107
- package/docs/tutorials/nlp_bpe_demo.md +0 -103
- package/docs/tutorials/nlp_mini_gpt_demo.md +0 -110
- package/docs/tutorials/nlp_viz.md +0 -76
- package/docs/tutorials/numerical_integration_demo.md +0 -65
- package/docs/tutorials/optimization_demo.md +0 -106
- package/docs/tutorials/pandas_io_demo.md +0 -160
- package/docs/tutorials/pca_demo.md +0 -87
- package/docs/tutorials/probability_demo.md +0 -48
- package/docs/tutorials/quantum_demo.md +0 -31
- package/docs/tutorials/quick_start.md +0 -44
- package/docs/tutorials/scientific_demo.md +0 -46
- package/docs/tutorials/signals_demo.md +0 -167
- package/docs/tutorials/stats_demo.md +0 -94
- package/docs/tutorials/stiff_ode_demo.md +0 -84
- package/docs/tutorials/time_series_demo.md +0 -145
- package/examples/core_demo.py +0 -40
- package/examples/data_analysis_demo.py +0 -60
- package/examples/diffeq_demo.py +0 -34
- package/examples/discovery_pipeline_demo.py +0 -57
- package/examples/ensemble_showcase.py +0 -81
- package/examples/fft2_demo.py +0 -32
- package/examples/graph_demo.py +0 -49
- package/examples/hypothesis_custom_generator.py +0 -121
- package/examples/hypothesis_demo.py +0 -48
- package/examples/hypothesis_tests_demo.py +0 -52
- package/examples/hypothesis_with_stats_demo.py +0 -43
- package/examples/interpolate_demo.py +0 -57
- package/examples/knowledge_demo.py +0 -100
- package/examples/linalg_demo.py +0 -61
- package/examples/math_utils_demo.py +0 -53
- package/examples/ml_and_viz_demo.py +0 -47
- package/examples/modeling_demo.py +0 -110
- package/examples/montecarlo_demo.py +0 -41
- package/examples/nlp_attention_demo.py +0 -168
- package/examples/nlp_bpe_demo.py +0 -79
- package/examples/nlp_mini_gpt_demo.py +0 -76
- package/examples/nlp_viz_demo.py +0 -98
- package/examples/numerical_integration_demo.py +0 -60
- package/examples/optimization_demo.py +0 -34
- package/examples/pca_demo.py +0 -124
- package/examples/pde_demo.py +0 -65
- package/examples/plot_demo.py +0 -84
- package/examples/plotting_notebook.ipynb +0 -87
- package/examples/probability_demo.py +0 -39
- package/examples/quantum_demo.py +0 -42
- package/examples/scientific_demo.py +0 -49
- package/examples/signals_demo.py +0 -86
- package/examples/stats_demo.py +0 -40
- package/examples/tour_of_numerical_methods.ipynb +0 -497
- package/mkdocs.yml +0 -159
- package/pyproject.toml +0 -288
- package/requirements-dev.lock +0 -427
- package/requirements-dev.txt +0 -39
- package/requirements.lock +0 -6
- package/requirements.txt +0 -13
- package/scripts/build_gif.py +0 -111
- package/scripts/build_video.py +0 -214
- package/scripts/cleanup_deployments.py +0 -173
- package/scripts/crop_readme_png.py +0 -40
- package/scripts/make_pi_dashboard.py +0 -316
- package/scripts/make_pi_gif.py +0 -138
- package/scripts/publish.py +0 -203
- package/scripts/render_promo.mjs +0 -93
- package/scripts/render_readme.py +0 -211
- package/scripts/render_readme_sections.py +0 -168
- package/scripts/verify_cli_install.py +0 -99
- package/scripts/verify_cookbook.py +0 -601
- package/scripts/verify_d1_numerics.py +0 -504
- package/scripts/verify_d2_edge_cases.py +0 -442
- package/scripts/verify_d4_hypothesis.py +0 -337
- package/scripts/verify_ml_reference.py +0 -160
- package/scripts/verify_pypi_release.py +0 -97
- package/scripts/verify_release_integrity.py +0 -194
- package/src/cds/__init__.py +0 -132
- package/src/cds/__main__.py +0 -8
- package/src/cds/_version.py +0 -11
- package/src/cds/bayes/__init__.py +0 -25
- package/src/cds/bayes/conjugate.py +0 -560
- package/src/cds/cli/__init__.py +0 -104
- package/src/cds/cli/__main__.py +0 -8
- package/src/cds/cli/_handlers.py +0 -323
- package/src/cds/cli/_parser.py +0 -155
- package/src/cds/cli/_style.py +0 -208
- package/src/cds/cli/_system_info.py +0 -71
- package/src/cds/core/__init__.py +0 -5
- package/src/cds/core/_numeric.py +0 -92
- package/src/cds/core/models.py +0 -166
- package/src/cds/data_analysis/__init__.py +0 -30
- package/src/cds/data_analysis/dataset.py +0 -122
- package/src/cds/data_analysis/loader.py +0 -75
- package/src/cds/data_analysis/pandas_io.py +0 -108
- package/src/cds/data_analysis/transform.py +0 -36
- package/src/cds/data_analysis/viz.py +0 -88
- package/src/cds/data_io/__init__.py +0 -27
- package/src/cds/data_io/streaming.py +0 -314
- package/src/cds/diffeq/__init__.py +0 -37
- package/src/cds/diffeq/_implicit.py +0 -349
- package/src/cds/diffeq/solvers.py +0 -312
- package/src/cds/diffeq/symplectic.py +0 -225
- package/src/cds/fractals/__init__.py +0 -34
- package/src/cds/fractals/sets.py +0 -356
- package/src/cds/genetics/__init__.py +0 -22
- package/src/cds/genetics/sequence.py +0 -199
- package/src/cds/graph/__init__.py +0 -31
- package/src/cds/graph/algorithms.py +0 -399
- package/src/cds/hypothesis/__init__.py +0 -51
- package/src/cds/hypothesis/evaluator.py +0 -311
- package/src/cds/hypothesis/generator.py +0 -275
- package/src/cds/hypothesis/mining.py +0 -314
- package/src/cds/infotheory/__init__.py +0 -25
- package/src/cds/infotheory/measures.py +0 -276
- package/src/cds/interpolate/__init__.py +0 -156
- package/src/cds/knowledge/__init__.py +0 -45
- package/src/cds/knowledge/graph.py +0 -489
- package/src/cds/knowledge/notes.py +0 -231
- package/src/cds/knowledge/retrieval.py +0 -339
- package/src/cds/math_utils/__init__.py +0 -46
- package/src/cds/math_utils/calculus.py +0 -40
- package/src/cds/math_utils/linalg.py +0 -496
- package/src/cds/math_utils/special.py +0 -167
- package/src/cds/math_utils/svd.py +0 -261
- package/src/cds/ml/__init__.py +0 -60
- package/src/cds/ml/boosting.py +0 -304
- package/src/cds/ml/clustering.py +0 -190
- package/src/cds/ml/decomposition.py +0 -172
- package/src/cds/ml/ensemble.py +0 -152
- package/src/cds/ml/linear_models.py +0 -225
- package/src/cds/ml/metrics.py +0 -227
- package/src/cds/ml/model_selection.py +0 -150
- package/src/cds/ml/naive_bayes.py +0 -179
- package/src/cds/ml/neighbors.py +0 -162
- package/src/cds/ml/neural.py +0 -204
- package/src/cds/ml/preprocessing.py +0 -131
- package/src/cds/ml/tree.py +0 -228
- package/src/cds/ml/voting.py +0 -175
- package/src/cds/modeling/__init__.py +0 -44
- package/src/cds/modeling/_base.py +0 -210
- package/src/cds/modeling/_nodes.py +0 -526
- package/src/cds/modeling/expression.py +0 -81
- package/src/cds/modeling/fitting.py +0 -477
- package/src/cds/modeling/model.py +0 -134
- package/src/cds/modeling/solver.py +0 -187
- package/src/cds/montecarlo/__init__.py +0 -24
- package/src/cds/montecarlo/markov.py +0 -112
- package/src/cds/montecarlo/methods.py +0 -294
- package/src/cds/nlp/__init__.py +0 -170
- package/src/cds/nlp/attention.py +0 -285
- package/src/cds/nlp/autograd/__init__.py +0 -70
- package/src/cds/nlp/autograd/_grad.py +0 -120
- package/src/cds/nlp/autograd/ops.py +0 -133
- package/src/cds/nlp/autograd/tensor.py +0 -298
- package/src/cds/nlp/bpe.py +0 -449
- package/src/cds/nlp/data.py +0 -70
- package/src/cds/nlp/embed.py +0 -190
- package/src/cds/nlp/layers.py +0 -259
- package/src/cds/nlp/model.py +0 -456
- package/src/cds/nlp/optim.py +0 -163
- package/src/cds/nlp/training.py +0 -167
- package/src/cds/nlp/viz.py +0 -254
- package/src/cds/numerical_integration/__init__.py +0 -31
- package/src/cds/numerical_integration/quadrature.py +0 -480
- package/src/cds/optimization/__init__.py +0 -26
- package/src/cds/optimization/_metaheuristics.py +0 -287
- package/src/cds/optimization/constrained.py +0 -212
- package/src/cds/optimization/minimize.py +0 -425
- package/src/cds/pde/__init__.py +0 -266
- package/src/cds/plot/__init__.py +0 -49
- package/src/cds/plot/_backend.py +0 -32
- package/src/cds/plot/charts.py +0 -462
- package/src/cds/probability/__init__.py +0 -65
- package/src/cds/probability/_advanced.py +0 -283
- package/src/cds/probability/distributions.py +0 -236
- package/src/cds/probability/extra_distributions.py +0 -199
- package/src/cds/provenance/__init__.py +0 -25
- package/src/cds/provenance/manifest.py +0 -355
- package/src/cds/py.typed +0 -0
- package/src/cds/quantum/__init__.py +0 -51
- package/src/cds/quantum/circuit.py +0 -122
- package/src/cds/quantum/multi_qubit.py +0 -310
- package/src/cds/quantum/simulator.py +0 -53
- package/src/cds/scientific/__init__.py +0 -34
- package/src/cds/scientific/constants.py +0 -35
- package/src/cds/scientific/formulas.py +0 -116
- package/src/cds/sensitivity.py +0 -204
- package/src/cds/signals/__init__.py +0 -59
- package/src/cds/signals/filters.py +0 -449
- package/src/cds/signals/processing.py +0 -224
- package/src/cds/signals/stft.py +0 -177
- package/src/cds/signals/wavelet.py +0 -146
- package/src/cds/stats/__init__.py +0 -99
- package/src/cds/stats/_distributions.py +0 -102
- package/src/cds/stats/bootstrap.py +0 -188
- package/src/cds/stats/descriptive.py +0 -172
- package/src/cds/stats/hypothesis_tests.py +0 -294
- package/src/cds/stats/nonparametric.py +0 -141
- package/src/cds/stats/power.py +0 -290
- package/src/cds/stats/regression.py +0 -51
- package/src/cds/stats/time_series.py +0 -420
- package/src/cds/tools/__init__.py +0 -29
- package/src/cds/tools/adapters.py +0 -218
- package/src/cds/tools/registry.py +0 -181
- package/src/cds/uncertainty/__init__.py +0 -17
- package/src/cds/uncertainty/propagation.py +0 -233
- package/src/cds/units/__init__.py +0 -45
- package/src/cds/units/core.py +0 -199
- package/src/cds/validation/__init__.py +0 -41
- package/src/cds/validation/adequacy.py +0 -157
- package/src/cds/validation/checks.py +0 -485
- package/src/cds/validation/report.py +0 -50
- package/src/cds/wavelets/__init__.py +0 -5
- package/src/cds/wavelets/haar.py +0 -219
- package/src/cds/workflow/__init__.py +0 -77
- package/src/cds/workflow/engine.py +0 -116
- package/src/cds/workflow/gates.py +0 -120
- package/src/cds/workflow/orchestrator.py +0 -431
- package/src/cds/workflow/selection.py +0 -454
- package/src/cds/workflow/tooling.py +0 -155
- package/src/cds/workflow/types.py +0 -107
- package/tests/__init__.py +0 -0
- package/tests/conftest.py +0 -109
- package/tests/test_advanced_fitting.py +0 -247
- package/tests/test_audit_completion_coverage.py +0 -183
- package/tests/test_audit_guard_coverage.py +0 -115
- package/tests/test_audit_hardening.py +0 -138
- package/tests/test_audit_hardening_coverage.py +0 -111
- package/tests/test_bayes_v2.py +0 -208
- package/tests/test_benchmarks.py +0 -111
- package/tests/test_bootstrap.py +0 -135
- package/tests/test_cli.py +0 -51
- package/tests/test_cli_color.py +0 -114
- package/tests/test_cli_extended.py +0 -239
- package/tests/test_cli_system_info.py +0 -36
- package/tests/test_constrained_opt.py +0 -174
- package/tests/test_core.py +0 -273
- package/tests/test_data_analysis.py +0 -146
- package/tests/test_data_analysis_lazy_bridge.py +0 -68
- package/tests/test_data_analysis_pandas_io.py +0 -119
- package/tests/test_data_io.py +0 -149
- package/tests/test_dataset.py +0 -91
- package/tests/test_diffeq.py +0 -186
- package/tests/test_diffeq_implicit.py +0 -173
- package/tests/test_domain_validation.py +0 -66
- package/tests/test_edge_misc_numerical.py +0 -666
- package/tests/test_edge_ml_quantum_linalg.py +0 -191
- package/tests/test_edge_nlp.py +0 -229
- package/tests/test_edge_quantum_evaluator_cli.py +0 -601
- package/tests/test_edge_stats_optimization_signals.py +0 -406
- package/tests/test_extra_distributions.py +0 -206
- package/tests/test_fft2.py +0 -67
- package/tests/test_fitting_bootstrap.py +0 -202
- package/tests/test_fractals.py +0 -387
- package/tests/test_genetics.py +0 -159
- package/tests/test_graph.py +0 -380
- package/tests/test_hardening_privacy_provenance.py +0 -306
- package/tests/test_hypothesis.py +0 -216
- package/tests/test_hypothesis_engine.py +0 -59
- package/tests/test_hypothesis_mining.py +0 -247
- package/tests/test_hypothesis_tests.py +0 -277
- package/tests/test_infotheory.py +0 -302
- package/tests/test_interpolate.py +0 -189
- package/tests/test_knowledge.py +0 -1149
- package/tests/test_layering.py +0 -112
- package/tests/test_linalg_extended.py +0 -179
- package/tests/test_linalg_qr_cholesky.py +0 -68
- package/tests/test_markov.py +0 -155
- package/tests/test_math_utils.py +0 -157
- package/tests/test_ml_boosting.py +0 -148
- package/tests/test_ml_clustering.py +0 -92
- package/tests/test_ml_ensemble.py +0 -103
- package/tests/test_ml_knn.py +0 -95
- package/tests/test_ml_linreg.py +0 -70
- package/tests/test_ml_logreg.py +0 -84
- package/tests/test_ml_metrics.py +0 -125
- package/tests/test_ml_model_selection.py +0 -108
- package/tests/test_ml_naive_bayes.py +0 -183
- package/tests/test_ml_pca.py +0 -98
- package/tests/test_ml_preprocessing.py +0 -104
- package/tests/test_ml_tree.py +0 -89
- package/tests/test_ml_viz.py +0 -58
- package/tests/test_ml_voting.py +0 -219
- package/tests/test_modeling.py +0 -726
- package/tests/test_modeling_fit_validation.py +0 -46
- package/tests/test_montecarlo.py +0 -245
- package/tests/test_multi_qubit.py +0 -466
- package/tests/test_nlp_attention.py +0 -335
- package/tests/test_nlp_autograd.py +0 -435
- package/tests/test_nlp_bpe.py +0 -463
- package/tests/test_nlp_embed.py +0 -240
- package/tests/test_nlp_layers.py +0 -276
- package/tests/test_nlp_model.py +0 -172
- package/tests/test_nlp_training.py +0 -262
- package/tests/test_nlp_viz.py +0 -188
- package/tests/test_numerical_integration.py +0 -374
- package/tests/test_numerical_invariants.py +0 -768
- package/tests/test_numerical_oracles.py +0 -241
- package/tests/test_optimization.py +0 -139
- package/tests/test_optimization_metaheuristics.py +0 -221
- package/tests/test_pde.py +0 -294
- package/tests/test_plot_charts.py +0 -247
- package/tests/test_plot_lazy.py +0 -48
- package/tests/test_power.py +0 -226
- package/tests/test_probability.py +0 -274
- package/tests/test_probability_advanced.py +0 -226
- package/tests/test_property_invariants.py +0 -277
- package/tests/test_provenance.py +0 -215
- package/tests/test_provenance_audit_hardening.py +0 -45
- package/tests/test_public_api.py +0 -75
- package/tests/test_quantum.py +0 -195
- package/tests/test_release_contract.py +0 -105
- package/tests/test_retrieval.py +0 -255
- package/tests/test_scientific.py +0 -185
- package/tests/test_selection_audit_hardening.py +0 -55
- package/tests/test_sensitivity.py +0 -59
- package/tests/test_sensitivity_global.py +0 -73
- package/tests/test_signals.py +0 -146
- package/tests/test_signals_filters.py +0 -460
- package/tests/test_special_invariants.py +0 -222
- package/tests/test_special_numerics.py +0 -44
- package/tests/test_statistical_audit.py +0 -75
- package/tests/test_stats.py +0 -206
- package/tests/test_stats_audit_coverage.py +0 -17
- package/tests/test_stats_nonparametric.py +0 -87
- package/tests/test_stats_time_series.py +0 -352
- package/tests/test_stft.py +0 -208
- package/tests/test_streaming_analytics.py +0 -128
- package/tests/test_svd.py +0 -170
- package/tests/test_symplectic.py +0 -200
- package/tests/test_tool_adapters.py +0 -197
- package/tests/test_tools_registry.py +0 -132
- package/tests/test_uncertainty.py +0 -171
- package/tests/test_units.py +0 -139
- package/tests/test_validation.py +0 -100
- package/tests/test_validation_adequacy.py +0 -129
- package/tests/test_validation_advanced.py +0 -110
- package/tests/test_wavelet.py +0 -170
- package/tests/test_wavelets_v2.py +0 -119
- package/tests/test_workflow.py +0 -173
- package/tests/test_workflow_gates.py +0 -144
- package/tests/test_workflow_orchestrator.py +0 -516
- package/tests/test_workflow_orchestrator_blocked_review.py +0 -95
- package/tests/test_workflow_selection.py +0 -312
- package/tests/test_workflow_selection_coverage.py +0 -114
- package/tests/test_workflow_tooling.py +0 -190
package/src/cds/nlp/model.py
DELETED
|
@@ -1,456 +0,0 @@
|
|
|
1
|
-
"""A minimal GPT-from-scratch model in pure Python.
|
|
2
|
-
|
|
3
|
-
:class:`MiniGPT` is the smallest possible decoder-only transformer
|
|
4
|
-
that still does the right thing: a token embedding, a single causal
|
|
5
|
-
self-attention block, and a language-model head. It is a 50K-100K
|
|
6
|
-
parameter model — small enough to train in a few minutes on a CPU
|
|
7
|
-
and big enough to memorise the Shakespeare excerpt in
|
|
8
|
-
:mod:`cds.nlp.data`.
|
|
9
|
-
|
|
10
|
-
This module closes the loop on the educational NLP track:
|
|
11
|
-
BPE + sinusoidal embeddings + scaled-dot-product attention +
|
|
12
|
-
multi-head block + reverse-mode autograd + SGD/Adam + MiniGPT =
|
|
13
|
-
a learner can now watch a tiny GPT actually fit a corpus and
|
|
14
|
-
sample text from it, all in pure Python.
|
|
15
|
-
|
|
16
|
-
Scope:
|
|
17
|
-
* :class:`MiniGPT` — token embedding + 1 causal block + LM head
|
|
18
|
-
* :func:`cross_entropy` (re-exported from :mod:`cds.nlp.training`)
|
|
19
|
-
* Inference via :meth:`MiniGPT.sample`
|
|
20
|
-
|
|
21
|
-
Out of scope for the educational track:
|
|
22
|
-
* Multi-layer stacks (N blocks) — straightforward to add but
|
|
23
|
-
quadratic in N for the educational engine.
|
|
24
|
-
* Dropout, ALiBi, RoPE, GQA, sliding window — modern refinements
|
|
25
|
-
not on the educational critical path.
|
|
26
|
-
* KV-cache — required for efficient long-context inference; the
|
|
27
|
-
full corpus here is short enough that re-running forward is fine.
|
|
28
|
-
"""
|
|
29
|
-
|
|
30
|
-
from __future__ import annotations
|
|
31
|
-
|
|
32
|
-
import math
|
|
33
|
-
|
|
34
|
-
from cds.core._numeric import LAYERNORM_EPS, SAMPLING_TEMPERATURE_EPS
|
|
35
|
-
from cds.nlp.attention import causal_mask
|
|
36
|
-
from cds.nlp.autograd import Parameter, Tensor, exp, log
|
|
37
|
-
from cds.nlp.embed import PositionalEncoding
|
|
38
|
-
|
|
39
|
-
__all__ = ["MiniGPT", "sample"]
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
# ---------------------------------------------------------------------- #
|
|
43
|
-
# MiniGPT
|
|
44
|
-
# ---------------------------------------------------------------------- #
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
class MiniGPT:
|
|
48
|
-
"""One-block decoder-only transformer for char-level language modelling.
|
|
49
|
-
|
|
50
|
-
Architecture:
|
|
51
|
-
token embedding (vocab_size x d_model)
|
|
52
|
-
sinusoidal positions (max_len x d_model)
|
|
53
|
-
one transformer block (multi-head causal self-attention + FFN)
|
|
54
|
-
linear LM head (d_model x vocab_size)
|
|
55
|
-
|
|
56
|
-
Total parameters scale as
|
|
57
|
-
``vocab_size * d_model + d_model^2 * 4 + d_model * d_ff + d_model * vocab_size``,
|
|
58
|
-
which for the default ``d_model=32, n_heads=2, d_ff=64`` is
|
|
59
|
-
~5K-50K — small enough to fit in a fresh clone and train
|
|
60
|
-
in a few minutes on a CPU.
|
|
61
|
-
|
|
62
|
-
Args:
|
|
63
|
-
vocab_size: Number of distinct tokens.
|
|
64
|
-
d_model: Embedding width and hidden size.
|
|
65
|
-
n_heads: Number of attention heads. Must divide ``d_model``.
|
|
66
|
-
d_ff: Position-wise FFN hidden width. Default ``4 * d_model``.
|
|
67
|
-
max_len: Maximum sequence length the model can handle.
|
|
68
|
-
seed: RNG seed used for the random initialisation.
|
|
69
|
-
"""
|
|
70
|
-
|
|
71
|
-
def __init__(
|
|
72
|
-
self,
|
|
73
|
-
vocab_size: int,
|
|
74
|
-
d_model: int = 32,
|
|
75
|
-
n_heads: int = 2,
|
|
76
|
-
d_ff: int = 64,
|
|
77
|
-
max_len: int = 64,
|
|
78
|
-
seed: int = 0xC0DE,
|
|
79
|
-
) -> None:
|
|
80
|
-
"""Validate dimensions and build the embedding/encoder/head sub-layers.
|
|
81
|
-
|
|
82
|
-
See the class docstring for the meaning of each argument.
|
|
83
|
-
"""
|
|
84
|
-
if d_model % n_heads != 0:
|
|
85
|
-
raise ValueError(f"d_model {d_model} must be divisible by n_heads {n_heads}")
|
|
86
|
-
if d_ff < 1:
|
|
87
|
-
raise ValueError(f"d_ff must be >= 1, got {d_ff}")
|
|
88
|
-
if max_len < 1:
|
|
89
|
-
raise ValueError(f"max_len must be >= 1, got {max_len}")
|
|
90
|
-
|
|
91
|
-
self.vocab_size = vocab_size
|
|
92
|
-
self.d_model = d_model
|
|
93
|
-
self.n_heads = n_heads
|
|
94
|
-
self.d_ff = d_ff
|
|
95
|
-
self.max_len = max_len
|
|
96
|
-
|
|
97
|
-
import random
|
|
98
|
-
|
|
99
|
-
rng = random.Random(seed)
|
|
100
|
-
|
|
101
|
-
# Xavier-uniform-ish init for matrices, zero for biases.
|
|
102
|
-
def _rand_matrix(rows: int, cols: int) -> list[list[float]]:
|
|
103
|
-
bound = 1.0 / math.sqrt(cols)
|
|
104
|
-
return [[rng.uniform(-bound, bound) for _ in range(cols)] for _ in range(rows)]
|
|
105
|
-
|
|
106
|
-
# Token embedding: each row is the d_model vector for a token id.
|
|
107
|
-
# Represented as a list of Parameters (one per row) so the
|
|
108
|
-
# optimiser sees them as trainable.
|
|
109
|
-
self.token_embedding: list[list[Parameter]] = [
|
|
110
|
-
[Parameter(v) for v in row] for row in _rand_matrix(vocab_size, d_model)
|
|
111
|
-
]
|
|
112
|
-
# Projections: (d_model x d_model) for Q, K, V, output.
|
|
113
|
-
self.w_q = [[Parameter(v) for v in row] for row in _rand_matrix(d_model, d_model)]
|
|
114
|
-
self.w_k = [[Parameter(v) for v in row] for row in _rand_matrix(d_model, d_model)]
|
|
115
|
-
self.w_v = [[Parameter(v) for v in row] for row in _rand_matrix(d_model, d_model)]
|
|
116
|
-
self.w_o = [[Parameter(v) for v in row] for row in _rand_matrix(d_model, d_model)]
|
|
117
|
-
# LayerNorm parameters (gamma=1, beta=0 default).
|
|
118
|
-
self.ln1_gamma = [Parameter(1.0) for _ in range(d_model)]
|
|
119
|
-
self.ln1_beta = [Parameter(0.0) for _ in range(d_model)]
|
|
120
|
-
self.ln2_gamma = [Parameter(1.0) for _ in range(d_model)]
|
|
121
|
-
self.ln2_beta = [Parameter(0.0) for _ in range(d_model)]
|
|
122
|
-
# FFN: 2-layer with GeLU.
|
|
123
|
-
self.w1 = [[Parameter(v) for v in row] for row in _rand_matrix(d_model, d_ff)]
|
|
124
|
-
self.b1 = [Parameter(0.0) for _ in range(d_ff)]
|
|
125
|
-
self.w2 = [[Parameter(v) for v in row] for row in _rand_matrix(d_ff, d_model)]
|
|
126
|
-
self.b2 = [Parameter(0.0) for _ in range(d_model)]
|
|
127
|
-
# LM head: d_model -> vocab_size.
|
|
128
|
-
self.w_head = [[Parameter(v) for v in row] for row in _rand_matrix(d_model, vocab_size)]
|
|
129
|
-
self.b_head = [Parameter(0.0) for _ in range(vocab_size)]
|
|
130
|
-
|
|
131
|
-
# Fixed sinusoidal position encoding (no trainable parameters).
|
|
132
|
-
self.pos = PositionalEncoding(max_len=max_len, d_model=d_model)
|
|
133
|
-
|
|
134
|
-
# ------------------------------------------------------------------ #
|
|
135
|
-
# Parameter collection
|
|
136
|
-
# ------------------------------------------------------------------ #
|
|
137
|
-
|
|
138
|
-
def parameters(self) -> list[Parameter]:
|
|
139
|
-
"""All trainable parameters (in the order the optimiser should walk)."""
|
|
140
|
-
params: list[Parameter] = []
|
|
141
|
-
for row in self.token_embedding:
|
|
142
|
-
params.extend(row)
|
|
143
|
-
for mat in (self.w_q, self.w_k, self.w_v, self.w_o, self.w1, self.w2, self.w_head):
|
|
144
|
-
for row in mat:
|
|
145
|
-
params.extend(row)
|
|
146
|
-
params.extend(self.ln1_gamma)
|
|
147
|
-
params.extend(self.ln1_beta)
|
|
148
|
-
params.extend(self.ln2_gamma)
|
|
149
|
-
params.extend(self.ln2_beta)
|
|
150
|
-
params.extend(self.b1)
|
|
151
|
-
params.extend(self.b2)
|
|
152
|
-
params.extend(self.b_head)
|
|
153
|
-
return params
|
|
154
|
-
|
|
155
|
-
# ------------------------------------------------------------------ #
|
|
156
|
-
# Forward pass
|
|
157
|
-
# ------------------------------------------------------------------ #
|
|
158
|
-
|
|
159
|
-
def forward(self, ids: list[int]) -> list[Tensor]:
|
|
160
|
-
"""Run one forward pass; return ``vocab_size`` logits for the
|
|
161
|
-
last position only (a language model predicts the next
|
|
162
|
-
token from the *final* position's hidden state).
|
|
163
|
-
|
|
164
|
-
For the educational track we keep the autograd graph attached
|
|
165
|
-
to the returned logits, so :func:`cds.nlp.training.cross_entropy`
|
|
166
|
-
can chain back to every parameter.
|
|
167
|
-
"""
|
|
168
|
-
if not ids:
|
|
169
|
-
return []
|
|
170
|
-
if len(ids) > self.max_len:
|
|
171
|
-
raise ValueError(f"sequence length {len(ids)} exceeds max_len {self.max_len}")
|
|
172
|
-
n = len(ids)
|
|
173
|
-
d = self.d_model
|
|
174
|
-
|
|
175
|
-
# Token + position embedding. The position encoding is a fixed
|
|
176
|
-
# pure-Python matrix; we lift it to the autograd world by
|
|
177
|
-
# promoting each entry to a constant Tensor.
|
|
178
|
-
token_vecs: list[list[Tensor]] = [
|
|
179
|
-
[self.token_embedding[t][j] for j in range(d)] for t in ids
|
|
180
|
-
]
|
|
181
|
-
pos_vecs: list[list[Tensor]] = [
|
|
182
|
-
[Tensor(data=self.pos.matrix[i][j], requires_grad=False) for j in range(d)]
|
|
183
|
-
for i in range(n)
|
|
184
|
-
]
|
|
185
|
-
x: list[list[Tensor]] = [
|
|
186
|
-
[token_vecs[i][j] + pos_vecs[i][j] for j in range(d)] for i in range(n)
|
|
187
|
-
]
|
|
188
|
-
|
|
189
|
-
# Causal multi-head self-attention + FFN with pre-norm.
|
|
190
|
-
normed = _layer_norm(x, self.ln1_gamma, self.ln1_beta)
|
|
191
|
-
attn_out = _multi_head_attention(
|
|
192
|
-
normed,
|
|
193
|
-
self.w_q,
|
|
194
|
-
self.w_k,
|
|
195
|
-
self.w_v,
|
|
196
|
-
self.w_o,
|
|
197
|
-
self.n_heads,
|
|
198
|
-
mask=causal_mask(n),
|
|
199
|
-
)
|
|
200
|
-
x = _add(x, attn_out)
|
|
201
|
-
normed2 = _layer_norm(x, self.ln2_gamma, self.ln2_beta)
|
|
202
|
-
ffn_out = _feed_forward(normed2, self.w1, self.b1, self.w2, self.b2)
|
|
203
|
-
x = _add(x, ffn_out)
|
|
204
|
-
|
|
205
|
-
# Use only the last position's hidden state for the LM head —
|
|
206
|
-
# predicting the next token only needs the rightmost context.
|
|
207
|
-
last = x[-1]
|
|
208
|
-
# Linear: logits = last @ w_head + b_head
|
|
209
|
-
logits: list[Tensor] = []
|
|
210
|
-
for v in range(self.vocab_size):
|
|
211
|
-
acc: Tensor = self.b_head[v] + Tensor(data=0.0, requires_grad=False)
|
|
212
|
-
for j in range(d):
|
|
213
|
-
acc = acc + last[j] * self.w_head[j][v]
|
|
214
|
-
logits.append(acc)
|
|
215
|
-
return logits
|
|
216
|
-
|
|
217
|
-
# ------------------------------------------------------------------ #
|
|
218
|
-
# Sampling
|
|
219
|
-
# ------------------------------------------------------------------ #
|
|
220
|
-
|
|
221
|
-
def sample(self, prompt_ids: list[int], n_tokens: int, temperature: float = 1.0) -> list[int]:
|
|
222
|
-
"""Generate ``n_tokens`` new ids after ``prompt_ids``.
|
|
223
|
-
|
|
224
|
-
Uses simple multinomial sampling: convert the last-position
|
|
225
|
-
logits to probabilities via :func:`softmax`, sample one
|
|
226
|
-
token, append, repeat. The forward pass runs with
|
|
227
|
-
``requires_grad=False`` so no graph is built.
|
|
228
|
-
"""
|
|
229
|
-
from cds.nlp.training import softmax
|
|
230
|
-
|
|
231
|
-
if n_tokens <= 0:
|
|
232
|
-
return list(prompt_ids)
|
|
233
|
-
ids = list(prompt_ids)
|
|
234
|
-
for _ in range(n_tokens):
|
|
235
|
-
# Trim to the last ``max_len`` tokens so we don't exceed
|
|
236
|
-
# the model's positional window.
|
|
237
|
-
ctx = ids[-self.max_len :]
|
|
238
|
-
logits = self.forward(ctx)
|
|
239
|
-
# Drop the graph — we only need the numbers.
|
|
240
|
-
vals = [li.data for li in logits]
|
|
241
|
-
if temperature != 1.0:
|
|
242
|
-
vals = [v / max(temperature, SAMPLING_TEMPERATURE_EPS) for v in vals]
|
|
243
|
-
probs = softmax(vals)
|
|
244
|
-
# Deterministic argmax for the educational default;
|
|
245
|
-
# callers that want sampling can pass a temperature
|
|
246
|
-
# and a custom sampler via the public hooks.
|
|
247
|
-
nxt = max(range(len(probs)), key=lambda i: probs[i])
|
|
248
|
-
ids.append(nxt)
|
|
249
|
-
return ids
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
# ---------------------------------------------------------------------- #
|
|
253
|
-
# Internal helpers (lift the float-only ops from cds.nlp.layers to
|
|
254
|
-
# operate on Tensor rows so the autograd graph stays connected)
|
|
255
|
-
# ---------------------------------------------------------------------- #
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
def _layer_norm(
|
|
259
|
-
x: list[list[Tensor]],
|
|
260
|
-
gamma: list[Parameter],
|
|
261
|
-
beta: list[Parameter],
|
|
262
|
-
) -> list[list[Tensor]]:
|
|
263
|
-
d = len(x[0])
|
|
264
|
-
if len(gamma) != d or len(beta) != d:
|
|
265
|
-
raise ValueError("gamma/beta length mismatch")
|
|
266
|
-
out: list[list[Tensor]] = []
|
|
267
|
-
for row in x:
|
|
268
|
-
inv_d = 1.0 / d
|
|
269
|
-
mean = _sum_tensors(row) * inv_d
|
|
270
|
-
diffs = [row[j] - mean for j in range(d)]
|
|
271
|
-
var = _sum_tensors([diffs[j] * diffs[j] for j in range(d)]) * inv_d
|
|
272
|
-
std = _exp(0.5 * _log(var + LAYERNORM_EPS))
|
|
273
|
-
out.append([gamma[j] * diffs[j] / std + beta[j] for j in range(d)])
|
|
274
|
-
return out
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
def _sum_tensors(ts: list[Tensor]) -> Tensor:
|
|
278
|
-
acc = Tensor(data=0.0, requires_grad=False)
|
|
279
|
-
for t in ts:
|
|
280
|
-
acc = acc + t
|
|
281
|
-
return acc
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
def _exp(x: Tensor) -> Tensor:
|
|
285
|
-
return exp(x)
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
def _log(x: Tensor) -> Tensor:
|
|
289
|
-
return log(x)
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
def _add(a: list[list[Tensor]], b: list[list[Tensor]]) -> list[list[Tensor]]:
|
|
293
|
-
n = len(a)
|
|
294
|
-
d = len(a[0])
|
|
295
|
-
return [[a[i][j] + b[i][j] for j in range(d)] for i in range(n)]
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
def _multi_head_attention(
|
|
299
|
-
x: list[list[Tensor]],
|
|
300
|
-
w_q: list[list[Parameter]],
|
|
301
|
-
w_k: list[list[Parameter]],
|
|
302
|
-
w_v: list[list[Parameter]],
|
|
303
|
-
w_o: list[list[Parameter]],
|
|
304
|
-
n_heads: int,
|
|
305
|
-
mask: list[list[float]] | None = None,
|
|
306
|
-
) -> list[list[Tensor]]:
|
|
307
|
-
"""Multi-head self-attention on Tensor rows.
|
|
308
|
-
|
|
309
|
-
Lifts the pure-Python attention from ``cds.nlp.attention`` to
|
|
310
|
-
operate on Tensor rows so the autograd graph stays attached.
|
|
311
|
-
"""
|
|
312
|
-
d = len(x[0])
|
|
313
|
-
d_head = d // n_heads
|
|
314
|
-
|
|
315
|
-
# Project to Q, K, V via a tiny "matvec" inner loop.
|
|
316
|
-
def _project(x_row: list[Tensor], w: list[list[Parameter]]) -> list[Tensor]:
|
|
317
|
-
out: list[Tensor] = []
|
|
318
|
-
for i in range(len(w)):
|
|
319
|
-
acc = Tensor(data=0.0, requires_grad=False)
|
|
320
|
-
for j in range(len(w[i])):
|
|
321
|
-
acc = acc + x_row[j] * w[i][j]
|
|
322
|
-
out.append(acc)
|
|
323
|
-
return out
|
|
324
|
-
|
|
325
|
-
q_rows = [_project(x[i], w_q) for i in range(len(x))]
|
|
326
|
-
k_rows = [_project(x[i], w_k) for i in range(len(x))]
|
|
327
|
-
v_rows = [_project(x[i], w_v) for i in range(len(x))]
|
|
328
|
-
|
|
329
|
-
# Split heads: (n, d) → (n, n_heads, d_head) → (n_heads, n, d_head).
|
|
330
|
-
def _split(rows: list[list[Tensor]]) -> list[list[list[Tensor]]]:
|
|
331
|
-
n = len(rows)
|
|
332
|
-
return [
|
|
333
|
-
[[rows[i][h * d_head + j] for j in range(d_head)] for i in range(n)]
|
|
334
|
-
for h in range(n_heads)
|
|
335
|
-
]
|
|
336
|
-
|
|
337
|
-
qh, kh, vh = _split(q_rows), _split(k_rows), _split(v_rows)
|
|
338
|
-
|
|
339
|
-
# Per-head attention with causal mask.
|
|
340
|
-
head_outs: list[list[list[Tensor]]] = []
|
|
341
|
-
for h in range(n_heads):
|
|
342
|
-
head_outs.append(_scaled_dot_product(qh[h], kh[h], vh[h], mask))
|
|
343
|
-
|
|
344
|
-
# Concat heads (n_heads, n, d_head) → (n, d).
|
|
345
|
-
n = len(x)
|
|
346
|
-
merged: list[list[Tensor]] = [[] for _ in range(n)]
|
|
347
|
-
for i in range(n):
|
|
348
|
-
row: list[Tensor] = []
|
|
349
|
-
for h in range(n_heads):
|
|
350
|
-
row.extend(head_outs[h][i])
|
|
351
|
-
merged[i] = row
|
|
352
|
-
|
|
353
|
-
# Output projection.
|
|
354
|
-
return [_project(merged[i], w_o) for i in range(n)]
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
def _scaled_dot_product(
|
|
358
|
-
q: list[list[Tensor]],
|
|
359
|
-
k: list[list[Tensor]],
|
|
360
|
-
v: list[list[Tensor]],
|
|
361
|
-
mask: list[list[float]] | None = None,
|
|
362
|
-
) -> list[list[Tensor]]:
|
|
363
|
-
d_k = len(q[0])
|
|
364
|
-
n = len(q)
|
|
365
|
-
scale = 1.0 / math.sqrt(d_k)
|
|
366
|
-
# scores[i][t] = sum_j q[i][j] * k[t][j] * scale + (mask[i][t] if mask else 0)
|
|
367
|
-
k_t: list[list[Tensor]] = [[k[t][j] for t in range(n)] for j in range(d_k)]
|
|
368
|
-
scores: list[list[Tensor]] = []
|
|
369
|
-
for i in range(n):
|
|
370
|
-
row: list[Tensor] = []
|
|
371
|
-
for t in range(n):
|
|
372
|
-
acc = Tensor(data=0.0, requires_grad=False)
|
|
373
|
-
for j in range(d_k):
|
|
374
|
-
acc = acc + q[i][j] * k_t[j][t]
|
|
375
|
-
row.append(acc * scale)
|
|
376
|
-
if mask is not None:
|
|
377
|
-
for t in range(n):
|
|
378
|
-
m = mask[i][t]
|
|
379
|
-
if m != 0.0:
|
|
380
|
-
# m == -inf → add a very large negative constant
|
|
381
|
-
# to make softmax collapse the weight. (Pure-Python
|
|
382
|
-
# doesn't have float("-inf") reliably; we use a
|
|
383
|
-
# big negative number.)
|
|
384
|
-
row[t] = row[t] + Tensor(data=-1e9, requires_grad=False)
|
|
385
|
-
scores.append(row)
|
|
386
|
-
# Softmax row-wise.
|
|
387
|
-
weights: list[list[Tensor]] = [_softmax_row(r) for r in scores]
|
|
388
|
-
# context = weights @ v.
|
|
389
|
-
out: list[list[Tensor]] = []
|
|
390
|
-
for i in range(n):
|
|
391
|
-
row = [Tensor(data=0.0, requires_grad=False) for _ in range(len(v[0]))]
|
|
392
|
-
for t in range(n):
|
|
393
|
-
for j in range(len(v[t])):
|
|
394
|
-
row[j] = row[j] + weights[i][t] * v[t][j]
|
|
395
|
-
out.append(row)
|
|
396
|
-
return out
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
def _softmax_row(row: list[Tensor]) -> list[Tensor]:
|
|
400
|
-
m = max(t.data for t in row)
|
|
401
|
-
m_const = Tensor(data=m, requires_grad=False)
|
|
402
|
-
exps = [exp(row[i] - m_const) for i in range(len(row))]
|
|
403
|
-
total = _sum_tensors(exps)
|
|
404
|
-
return [e / total for e in exps]
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
def _feed_forward(
|
|
408
|
-
x: list[list[Tensor]],
|
|
409
|
-
w1: list[list[Parameter]],
|
|
410
|
-
b1: list[Parameter],
|
|
411
|
-
w2: list[list[Parameter]],
|
|
412
|
-
b2: list[Parameter],
|
|
413
|
-
) -> list[list[Tensor]]:
|
|
414
|
-
d_model = len(x[0])
|
|
415
|
-
d_ff = len(b1)
|
|
416
|
-
# Hidden layer with GeLU.
|
|
417
|
-
h: list[list[Tensor]] = []
|
|
418
|
-
for i in range(len(x)):
|
|
419
|
-
row_i: list[Tensor] = []
|
|
420
|
-
for j in range(d_ff):
|
|
421
|
-
acc: Tensor = b1[j] + Tensor(data=0.0, requires_grad=False)
|
|
422
|
-
for k in range(d_model):
|
|
423
|
-
acc = acc + x[i][k] * w1[k][j]
|
|
424
|
-
# GeLU on the autograd-free side: lift the scalar to a
|
|
425
|
-
# constant Tensor. (FFN non-linearities in the
|
|
426
|
-
# educational engine are detached — keeps the autograd
|
|
427
|
-
# graph tractable for a tiny demo. The activation itself
|
|
428
|
-
# is exact via math.erf.)
|
|
429
|
-
row_i.append(Tensor(data=_gelu_scalar(acc.data), requires_grad=False))
|
|
430
|
-
h.append(row_i)
|
|
431
|
-
# Output layer.
|
|
432
|
-
out: list[list[Tensor]] = []
|
|
433
|
-
for i in range(len(x)):
|
|
434
|
-
row_i2: list[Tensor] = []
|
|
435
|
-
for j in range(d_model):
|
|
436
|
-
acc = b2[j] + Tensor(data=0.0, requires_grad=False)
|
|
437
|
-
for k in range(d_ff):
|
|
438
|
-
acc = acc + h[i][k] * w2[k][j]
|
|
439
|
-
row_i2.append(acc)
|
|
440
|
-
out.append(row_i2)
|
|
441
|
-
return out
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
def _gelu_scalar(x: float) -> float:
|
|
445
|
-
return 0.5 * x * (1.0 + math.erf(x / math.sqrt(2.0)))
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
# ---------------------------------------------------------------------- #
|
|
449
|
-
# Convenience sampler
|
|
450
|
-
# ---------------------------------------------------------------------- #
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
def sample(model: MiniGPT, prompt_ids: list[int], n_tokens: int) -> list[int]:
|
|
454
|
-
"""Convenience wrapper around :meth:`MiniGPT.sample` for callers
|
|
455
|
-
that don't want to dig through the class API."""
|
|
456
|
-
return model.sample(prompt_ids, n_tokens)
|
package/src/cds/nlp/optim.py
DELETED
|
@@ -1,163 +0,0 @@
|
|
|
1
|
-
"""Optimizers for the cds.nlp autograd engine.
|
|
2
|
-
|
|
3
|
-
Two optimizers in the educational NLP track:
|
|
4
|
-
|
|
5
|
-
* :class:`SGD` — stochastic gradient descent with optional momentum
|
|
6
|
-
and weight decay. The minimum useful optimizer; matches
|
|
7
|
-
Karpathy's micrograd ``Optimizer`` semantics.
|
|
8
|
-
* :class:`Adam` — adaptive moment estimation (Kingma & Ba 2014).
|
|
9
|
-
The default for transformer training. Uses bias-corrected first
|
|
10
|
-
and second moment estimates stored on the :class:`cds.nlp.autograd.Tensor`
|
|
11
|
-
itself, so the optimizer's state is just a list of :class:`Parameter`
|
|
12
|
-
references.
|
|
13
|
-
|
|
14
|
-
Both optimizers operate on :class:`Parameter` objects — thin
|
|
15
|
-
:func:`cds.nlp.autograd.Tensor` wrappers that the model exposes as
|
|
16
|
-
its trainable weights. Use :func:`parameters` to collect them.
|
|
17
|
-
|
|
18
|
-
References:
|
|
19
|
-
- Kingma, D. P., & Ba, J. (2014). "Adam: A Method for Stochastic
|
|
20
|
-
Optimization." arXiv:1412.6980.
|
|
21
|
-
- PyTorch's ``torch.optim`` docs — for the parameter-group API
|
|
22
|
-
shape this module imitates (one ``Tensor`` per parameter;
|
|
23
|
-
no per-parameter options in the educational track).
|
|
24
|
-
"""
|
|
25
|
-
|
|
26
|
-
from __future__ import annotations
|
|
27
|
-
|
|
28
|
-
import math
|
|
29
|
-
from collections.abc import Iterable
|
|
30
|
-
from dataclasses import dataclass, field
|
|
31
|
-
from typing import TYPE_CHECKING
|
|
32
|
-
|
|
33
|
-
from cds.core._numeric import ADAM_DEFAULT_BETAS, ADAM_DEFAULT_EPS, ADAM_DEFAULT_LR, SGD_DEFAULT_LR
|
|
34
|
-
|
|
35
|
-
if TYPE_CHECKING:
|
|
36
|
-
from cds.nlp.autograd import Tensor
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
__all__ = ["SGD", "Adam"]
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
@dataclass
|
|
43
|
-
class SGD:
|
|
44
|
-
"""Stochastic gradient descent with optional momentum.
|
|
45
|
-
|
|
46
|
-
Args:
|
|
47
|
-
params: Iterable of :class:`Parameter` (or any
|
|
48
|
-
:class:`cds.nlp.autograd.Tensor` with ``requires_grad=True``)
|
|
49
|
-
to update.
|
|
50
|
-
lr: Learning rate. Must be positive.
|
|
51
|
-
momentum: Momentum factor in ``[0, 1)``. ``0`` reduces to
|
|
52
|
-
vanilla SGD. ``> 0`` updates each parameter with
|
|
53
|
-
``v = momentum * v + grad; p -= lr * v``.
|
|
54
|
-
weight_decay: Optional L2 penalty coefficient. Adds
|
|
55
|
-
``weight_decay * p.data`` to the gradient at every step.
|
|
56
|
-
"""
|
|
57
|
-
|
|
58
|
-
params: list[Tensor]
|
|
59
|
-
lr: float = SGD_DEFAULT_LR
|
|
60
|
-
momentum: float = 0.0
|
|
61
|
-
weight_decay: float = 0.0
|
|
62
|
-
_velocities: list[float] = field(init=False, default_factory=list)
|
|
63
|
-
|
|
64
|
-
def __post_init__(self) -> None:
|
|
65
|
-
"""Validate hyperparameters and allocate one velocity slot per parameter."""
|
|
66
|
-
if self.lr <= 0:
|
|
67
|
-
raise ValueError(f"lr must be > 0, got {self.lr}")
|
|
68
|
-
if not 0.0 <= self.momentum < 1.0:
|
|
69
|
-
raise ValueError(f"momentum must be in [0, 1), got {self.momentum}")
|
|
70
|
-
if self.weight_decay < 0:
|
|
71
|
-
raise ValueError(f"weight_decay must be >= 0, got {self.weight_decay}")
|
|
72
|
-
# Allocate a velocity slot per parameter.
|
|
73
|
-
self._velocities = [0.0] * len(self.params)
|
|
74
|
-
|
|
75
|
-
def step(self) -> None:
|
|
76
|
-
"""Apply one update to each parameter.
|
|
77
|
-
|
|
78
|
-
Must be called *after* ``loss.backward()`` and *before*
|
|
79
|
-
``zero_grad()`` — otherwise the gradient buffer will be
|
|
80
|
-
overwritten on the next forward pass.
|
|
81
|
-
"""
|
|
82
|
-
for i, p in enumerate(self.params):
|
|
83
|
-
grad = p.grad + self.weight_decay * p.data if self.weight_decay else p.grad
|
|
84
|
-
if self.momentum == 0.0:
|
|
85
|
-
p.data -= self.lr * grad
|
|
86
|
-
else:
|
|
87
|
-
self._velocities[i] = self.momentum * self._velocities[i] + grad
|
|
88
|
-
p.data -= self.lr * self._velocities[i]
|
|
89
|
-
|
|
90
|
-
def zero_grad(self) -> None:
|
|
91
|
-
"""Reset all parameter gradients to 0. Call between batches."""
|
|
92
|
-
for p in self.params:
|
|
93
|
-
p.grad = 0.0
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
@dataclass
|
|
97
|
-
class Adam:
|
|
98
|
-
"""Adam optimiser (Kingma & Ba 2014).
|
|
99
|
-
|
|
100
|
-
Maintains per-parameter first and second moment estimates with
|
|
101
|
-
bias correction. Defaults match the paper (``betas=(0.9, 0.999)``,
|
|
102
|
-
``eps=1e-8``).
|
|
103
|
-
|
|
104
|
-
Args:
|
|
105
|
-
params: Trainable parameters.
|
|
106
|
-
lr: Learning rate. Typical values for transformer training
|
|
107
|
-
are in the ``3e-4`` to ``1e-3`` range.
|
|
108
|
-
betas: Coefficients for the first and second moment moving
|
|
109
|
-
averages.
|
|
110
|
-
eps: Epsilon for numerical stability in the denominator.
|
|
111
|
-
weight_decay: Optional L2 penalty coefficient.
|
|
112
|
-
"""
|
|
113
|
-
|
|
114
|
-
params: list[Tensor]
|
|
115
|
-
lr: float = ADAM_DEFAULT_LR
|
|
116
|
-
betas: tuple[float, float] = ADAM_DEFAULT_BETAS
|
|
117
|
-
eps: float = ADAM_DEFAULT_EPS
|
|
118
|
-
weight_decay: float = 0.0
|
|
119
|
-
_t: int = field(init=False, default=0)
|
|
120
|
-
_m: list[float] = field(init=False, default_factory=list)
|
|
121
|
-
_v: list[float] = field(init=False, default_factory=list)
|
|
122
|
-
|
|
123
|
-
def __post_init__(self) -> None:
|
|
124
|
-
"""Validate hyperparameters and zero-initialise the moment estimates."""
|
|
125
|
-
if self.lr <= 0:
|
|
126
|
-
raise ValueError(f"lr must be > 0, got {self.lr}")
|
|
127
|
-
if not (0.0 <= self.betas[0] < 1.0 and 0.0 <= self.betas[1] < 1.0):
|
|
128
|
-
raise ValueError(f"betas must each be in [0, 1), got {self.betas}")
|
|
129
|
-
if self.eps <= 0:
|
|
130
|
-
raise ValueError(f"eps must be > 0, got {self.eps}")
|
|
131
|
-
if self.weight_decay < 0:
|
|
132
|
-
raise ValueError(f"weight_decay must be >= 0, got {self.weight_decay}")
|
|
133
|
-
self._m = [0.0] * len(self.params)
|
|
134
|
-
self._v = [0.0] * len(self.params)
|
|
135
|
-
|
|
136
|
-
def step(self) -> None:
|
|
137
|
-
"""Apply one update. Increment step counter internally."""
|
|
138
|
-
self._t += 1
|
|
139
|
-
b1, b2 = self.betas
|
|
140
|
-
for i, p in enumerate(self.params):
|
|
141
|
-
grad = p.grad + self.weight_decay * p.data if self.weight_decay else p.grad
|
|
142
|
-
self._m[i] = b1 * self._m[i] + (1.0 - b1) * grad
|
|
143
|
-
self._v[i] = b2 * self._v[i] + (1.0 - b2) * (grad * grad)
|
|
144
|
-
# Bias correction — important in the first few hundred
|
|
145
|
-
# steps when the moving averages are still warming up.
|
|
146
|
-
m_hat = self._m[i] / (1.0 - b1**self._t)
|
|
147
|
-
v_hat = self._v[i] / (1.0 - b2**self._t)
|
|
148
|
-
p.data -= self.lr * m_hat / (math.sqrt(v_hat) + self.eps)
|
|
149
|
-
|
|
150
|
-
def zero_grad(self) -> None:
|
|
151
|
-
"""Reset ``.grad`` to ``0.0`` on every managed parameter."""
|
|
152
|
-
for p in self.params:
|
|
153
|
-
p.grad = 0.0
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
def parameters(items: Iterable[Tensor]) -> list[Tensor]:
|
|
157
|
-
"""Collect trainable tensors from a model.
|
|
158
|
-
|
|
159
|
-
Convenience helper — many models store their weights in
|
|
160
|
-
dictionaries or lists; this filters to ``requires_grad=True``
|
|
161
|
-
in one call.
|
|
162
|
-
"""
|
|
163
|
-
return [t for t in items if t.requires_grad]
|