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
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
# Machine Learning Tutorial
|
|
2
|
-
|
|
3
|
-
`cds.ml` ships a small, dependency-free multilayer perceptron (`MLP`) built on a
|
|
4
|
-
stack of `Layer` objects. Training uses the Adam optimizer from
|
|
5
|
-
[`cds.optimization`](optimization_demo.md), so the whole pipeline, forward
|
|
6
|
-
pass, backprop, and the optimizer step, is pure Python.
|
|
7
|
-
|
|
8
|
-
## 1. Build and inspect a network
|
|
9
|
-
|
|
10
|
-
Construct a layer with `(in_features, out_features, activation)`. Supported
|
|
11
|
-
activations are `relu`, `sigmoid`, and `tanh`. Stack them into an `MLP`.
|
|
12
|
-
|
|
13
|
-
```python
|
|
14
|
-
from cds.ml import MLP, Layer
|
|
15
|
-
|
|
16
|
-
# 2 inputs -> 4 hidden (ReLU) -> 1 output (Sigmoid)
|
|
17
|
-
net = MLP(
|
|
18
|
-
[
|
|
19
|
-
Layer(2, 4, activation="relu"),
|
|
20
|
-
Layer(4, 1, activation="sigmoid"),
|
|
21
|
-
]
|
|
22
|
-
)
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
## 2. Predict before training
|
|
26
|
-
|
|
27
|
-
`predict` takes a feature vector and returns the network's output.
|
|
28
|
-
|
|
29
|
-
```python
|
|
30
|
-
X = [[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]] # OR-gate inputs
|
|
31
|
-
y = [[0.0], [1.0], [1.0], [1.0]]
|
|
32
|
-
|
|
33
|
-
for xi in X:
|
|
34
|
-
print(f" In: {xi} -> Out: {net.predict(xi)[0]:.4f}")
|
|
35
|
-
# Untrained network outputs ≈ 0.5 everywhere:
|
|
36
|
-
# In: [0.0, 0.0] -> Out: 0.5000
|
|
37
|
-
# In: [0.0, 1.0] -> Out: 0.5159
|
|
38
|
-
# In: [1.0, 0.0] -> Out: 0.4839
|
|
39
|
-
# In: [1.0, 1.0] -> Out: 0.5249
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
## 3. Train with Adam
|
|
43
|
-
|
|
44
|
-
`train` runs Adam for `epochs` iterations over the dataset and returns a history
|
|
45
|
-
dict with the final loss, iteration count, and convergence flag.
|
|
46
|
-
|
|
47
|
-
```python
|
|
48
|
-
history = net.train(X, y, epochs=200, lr=0.1)
|
|
49
|
-
print(history)
|
|
50
|
-
# {'final_loss': 0.000403..., 'iterations': 200, 'converged': False}
|
|
51
|
-
|
|
52
|
-
for xi in X:
|
|
53
|
-
print(f" In: {xi} -> Out: {net.predict(xi)[0]:.4f}")
|
|
54
|
-
# After training the network has learned the OR function:
|
|
55
|
-
# In: [0.0, 0.0] -> Out: 0.0394
|
|
56
|
-
# In: [0.0, 1.0] -> Out: 0.9967
|
|
57
|
-
# In: [1.0, 0.0] -> Out: 0.9927
|
|
58
|
-
# In: [1.0, 1.0] -> Out: 1.0000
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
## 4. Resumable optimizer state
|
|
62
|
-
|
|
63
|
-
Internally, `train` stores Adam's moment estimates on the `MLP` instance
|
|
64
|
-
(`net.optimizer_state`). Calling `train` again resumes from that checkpoint
|
|
65
|
-
rather than restarting, so you can train in stages or lower the learning rate
|
|
66
|
-
between phases.
|
|
67
|
-
|
|
68
|
-
---
|
|
69
|
-
|
|
70
|
-
Run the full demo with `python examples/ml_and_viz_demo.py`.
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
# Mathematical Modeling Tutorial
|
|
2
|
-
|
|
3
|
-
`cds.modeling` provides a small symbolic algebra: build expressions, differentiate them symbolically, simplify, export to LaTeX, group them into a `MathModel`, and solve numerically.
|
|
4
|
-
|
|
5
|
-
## 1. Build & Evaluate an Expression
|
|
6
|
-
|
|
7
|
-
```python
|
|
8
|
-
from cds.modeling import Variable, Constant
|
|
9
|
-
|
|
10
|
-
x = Variable("x")
|
|
11
|
-
expr = x**2 + 3 * x # x^2 + 3x
|
|
12
|
-
print(expr.evaluate({"x": 2})) # 10.0
|
|
13
|
-
print(expr.to_str()) # ((x ** 2) + (3 * x))
|
|
14
|
-
```
|
|
15
|
-
|
|
16
|
-
## 2. Symbolic Differentiation
|
|
17
|
-
|
|
18
|
-
```python
|
|
19
|
-
from cds.modeling import Sin, Log, Exp
|
|
20
|
-
|
|
21
|
-
x = Variable("x")
|
|
22
|
-
f = Sin(x) * Exp(x) # sin(x) * e^x
|
|
23
|
-
df = f.diff("x") # symbolic derivative
|
|
24
|
-
print(df.to_str())
|
|
25
|
-
print(df.evaluate({"x": 0.0})) # 1.0 (analytically e^0*(sin0+cos0))
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
The chain, product, and quotient rules are all built in, for `Sin`, `Cos`, `Exp`, `Log`, `Sqrt`, `Pow`, and the arithmetic operators.
|
|
29
|
-
|
|
30
|
-
## 3. Simplify & Export to LaTeX
|
|
31
|
-
|
|
32
|
-
```python
|
|
33
|
-
from cds.modeling import Variable
|
|
34
|
-
|
|
35
|
-
x = Variable("x")
|
|
36
|
-
print((x + 0).simplify().to_str()) # x
|
|
37
|
-
print((x * 1).simplify().to_str()) # x
|
|
38
|
-
print((x**0).simplify().to_str()) # 1
|
|
39
|
-
|
|
40
|
-
expr = (Variable("x") ** Constant(2.0)) / Variable("y")
|
|
41
|
-
print(expr.to_latex()) # \frac{x^{2}}{y}
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
## 4. Group Equations into a MathModel
|
|
45
|
-
|
|
46
|
-
```python
|
|
47
|
-
from cds.modeling import MathModel, Variable
|
|
48
|
-
|
|
49
|
-
t, a = Variable("t"), Variable("a")
|
|
50
|
-
v0 = Variable("v0")
|
|
51
|
-
model = MathModel(
|
|
52
|
-
name="Kinematics",
|
|
53
|
-
description="Constant-acceleration motion",
|
|
54
|
-
parameters={"a": 9.81},
|
|
55
|
-
variables=["t", "v0", "x0"],
|
|
56
|
-
)
|
|
57
|
-
model.add_equation("velocity", v0 + a * t)
|
|
58
|
-
model.add_equation("position", Variable("x0") + v0 * t + 0.5 * a * t**2)
|
|
59
|
-
|
|
60
|
-
print(model.evaluate({"t": 2.0, "v0": 0.0, "x0": 0.0}))
|
|
61
|
-
# {'velocity': 19.62, 'position': 19.62}
|
|
62
|
-
|
|
63
|
-
# Jacobian column: how every equation depends on t
|
|
64
|
-
for label, d in model.jacobian("t").items():
|
|
65
|
-
print(label, d.to_str())
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
## 5. Solve & Fit
|
|
69
|
-
|
|
70
|
-
```python
|
|
71
|
-
from cds.modeling import Variable, solve_equation
|
|
72
|
-
|
|
73
|
-
# Solve x^2 - 2 = 0 => x = sqrt(2)
|
|
74
|
-
x = Variable("x")
|
|
75
|
-
result = solve_equation(x**2 - 2, variable="x", x0=1.0)
|
|
76
|
-
print(result.x) # ~1.4142
|
|
77
|
-
print(result.converged) # True
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
For fitting a model's parameters to data, see `cds.modeling.fit_parameters`, it minimizes the residual sum of squares via `cds.optimization.gradient_descent`.
|
|
81
|
-
|
|
82
|
-
Run the full demo with `python examples/modeling_demo.py`.
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
# Monte Carlo Methods Tutorial
|
|
2
|
-
|
|
3
|
-
`cds.montecarlo` estimates integrals, π, and random walks by sampling.
|
|
4
|
-
|
|
5
|
-
## 1. Estimating π
|
|
6
|
-
|
|
7
|
-
```python
|
|
8
|
-
import math
|
|
9
|
-
from cds.montecarlo import estimate_pi
|
|
10
|
-
|
|
11
|
-
r = estimate_pi(samples=100_000, seed=42)
|
|
12
|
-
print(r.estimate, abs(r.estimate - math.pi))
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
## 2. Integrating by Sampling
|
|
16
|
-
|
|
17
|
-
```python
|
|
18
|
-
from cds.montecarlo import mc_integrate
|
|
19
|
-
|
|
20
|
-
# ∫_0^1 x^2 dx = 1/3
|
|
21
|
-
print(mc_integrate(lambda x: x**2, a=0.0, b=1.0, samples=50_000, seed=7).value)
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
## 3. Random Walks
|
|
25
|
-
|
|
26
|
-
```python
|
|
27
|
-
from cds.montecarlo import random_walk_1d, random_walk_2d
|
|
28
|
-
|
|
29
|
-
print(random_walk_1d(steps=100, seed=1).position)
|
|
30
|
-
w2 = random_walk_2d(steps=100, seed=2)
|
|
31
|
-
print(w2.x, w2.y)
|
|
32
|
-
```
|
|
33
|
-
|
|
34
|
-
## 4. Buffon's Needle
|
|
35
|
-
|
|
36
|
-
```python
|
|
37
|
-
from cds.montecarlo import buffon_needle
|
|
38
|
-
|
|
39
|
-
print(buffon_needle(drops=10_000, needle_length=0.5, line_spacing=1.0, seed=3).pi_estimate)
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
Run the full demo with `python examples/montecarlo_demo.py`.
|
|
@@ -1,107 +0,0 @@
|
|
|
1
|
-
# Multi-Head Attention Tutorial
|
|
2
|
-
|
|
3
|
-
This demo extends the BPE + embeddings pipeline with a real **multi-head
|
|
4
|
-
self-attention block**, the core of the Transformer (Vaswani et al., 2017).
|
|
5
|
-
Everything runs in pure Python; the attention weights are dumped as an ASCII
|
|
6
|
-
heat map so the example is self-contained.
|
|
7
|
-
|
|
8
|
-
## 1. Tokenize and embed
|
|
9
|
-
|
|
10
|
-
Reuse the BPE tokenizer and positional embeddings from
|
|
11
|
-
[`nlp_bpe_demo.md`](nlp_bpe_demo.md):
|
|
12
|
-
|
|
13
|
-
```python
|
|
14
|
-
from cds.nlp import (
|
|
15
|
-
PositionalEncoding,
|
|
16
|
-
TokenEmbedding,
|
|
17
|
-
add_positional,
|
|
18
|
-
train_bpe,
|
|
19
|
-
)
|
|
20
|
-
|
|
21
|
-
corpus = (
|
|
22
|
-
"the quick brown fox jumps over the lazy dog "
|
|
23
|
-
"the quick brown fox jumps over the lazy dog "
|
|
24
|
-
"she sells seashells by the seashore "
|
|
25
|
-
"she sells seashells by the seashore "
|
|
26
|
-
)
|
|
27
|
-
tokenizer = train_bpe(corpus, vocab_size=80, min_frequency=2)
|
|
28
|
-
|
|
29
|
-
text = "the quick brown fox"
|
|
30
|
-
ids = tokenizer.encode(text) # [33, 45, 50, 53]
|
|
31
|
-
|
|
32
|
-
d_model = 16
|
|
33
|
-
table = TokenEmbedding(vocab_size=tokenizer.vocab_size, d_model=d_model)
|
|
34
|
-
pe = PositionalEncoding(max_len=len(ids) + 4, d_model=d_model)
|
|
35
|
-
combined = add_positional(table.forward(ids), pe)
|
|
36
|
-
# embedding shape: 4 x 16
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
## 2. Run multi-head attention with a causal mask
|
|
40
|
-
|
|
41
|
-
`multi_head_attention` takes linear projection weights (`w_q`, `w_k`, `w_v`,
|
|
42
|
-
`w_o`) and the number of heads. The `mask` argument here is a **causal mask**:
|
|
43
|
-
position `i` may only attend to positions `<= i`, which is what makes this a
|
|
44
|
-
*decoder-style* attention (used in GPT).
|
|
45
|
-
|
|
46
|
-
```python
|
|
47
|
-
from cds.nlp import causal_mask, multi_head_attention
|
|
48
|
-
|
|
49
|
-
n_heads = 2
|
|
50
|
-
# w_q, w_k, w_v, w_o are (d_model, d_model) weight matrices — see the
|
|
51
|
-
# example file for a small seeded initializer.
|
|
52
|
-
mask = causal_mask(len(ids))
|
|
53
|
-
output = multi_head_attention(combined, w_q, w_k, w_v, w_o, n_heads, mask=mask)
|
|
54
|
-
# attention output shape: 4 x 16
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
The scaled dot-product inside each head is
|
|
58
|
-
`softmax((Q Kᵀ) / √d_k) · V`, split across `n_heads` independent subspaces and
|
|
59
|
-
then re-projected through `w_o`.
|
|
60
|
-
|
|
61
|
-
## 3. Inspect the attention weights
|
|
62
|
-
|
|
63
|
-
The demo recomputes head-0's attention matrix and renders it as an ASCII heat
|
|
64
|
-
map (low → high: space `▁▂▃▄▅▆▇█`). Rows are query positions; bright cells are
|
|
65
|
-
high attention:
|
|
66
|
-
|
|
67
|
-
```
|
|
68
|
-
attention weights, head 0 (rows = query position):
|
|
69
|
-
█
|
|
70
|
-
▄▃
|
|
71
|
-
▃▂▂
|
|
72
|
-
▂▂▁▁
|
|
73
|
-
```
|
|
74
|
-
|
|
75
|
-
The lower-triangular pattern is the causal mask made visible, each row only
|
|
76
|
-
has non-zero weight up to its own column.
|
|
77
|
-
|
|
78
|
-
## 4. Verify the causal property
|
|
79
|
-
|
|
80
|
-
A clean invariant check: position 0's output must depend **only** on `v[0]`.
|
|
81
|
-
If we perturb `v[1:]`, position 0's output should not change:
|
|
82
|
-
|
|
83
|
-
```python
|
|
84
|
-
# Swap v at positions > 0 with random values, re-run attention.
|
|
85
|
-
assert abs(output[0][0] - alt_output[0][0]) < 1e-9
|
|
86
|
-
print("OK — output at position 0 is invariant under v[1:] changes")
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
```
|
|
90
|
-
verifying causal property at position 0…
|
|
91
|
-
first output dim: -0.053500
|
|
92
|
-
OK — output at position 0 is invariant under v[1:] changes
|
|
93
|
-
```
|
|
94
|
-
|
|
95
|
-
## Why it matters
|
|
96
|
-
|
|
97
|
-
This is the literal mechanism behind autoregressive language models. Because
|
|
98
|
-
the whole block is readable Python, you can step through the softmax, the
|
|
99
|
-
head-split, and the mask application to see exactly how information flows.
|
|
100
|
-
Continue to [`nlp_mini_gpt_demo.md`](nlp_mini_gpt_demo.md) to see attention
|
|
101
|
-
stacked into a full GPT and trained end-to-end.
|
|
102
|
-
|
|
103
|
-
Run the full demo:
|
|
104
|
-
|
|
105
|
-
```bash
|
|
106
|
-
python examples/nlp_attention_demo.py
|
|
107
|
-
```
|
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
# BPE Tokenizer & Embeddings Tutorial
|
|
2
|
-
|
|
3
|
-
`cds.nlp` is an educational NLP stack built from scratch: a Byte-Pair-Encoding
|
|
4
|
-
(BPE) tokenizer, sinusoidal positional encoding, and token embeddings, the
|
|
5
|
-
exact front-end a Transformer consumes. No HuggingFace, no NumPy.
|
|
6
|
-
|
|
7
|
-
## 1. Train a BPE tokenizer
|
|
8
|
-
|
|
9
|
-
`train_bpe` learns merge rules from a corpus by repeatedly merging the most
|
|
10
|
-
frequent adjacent pair, exactly as in the original Sennrich et al. (2016)
|
|
11
|
-
algorithm.
|
|
12
|
-
|
|
13
|
-
```python
|
|
14
|
-
from cds.nlp import train_bpe
|
|
15
|
-
|
|
16
|
-
corpus = (
|
|
17
|
-
"the quick brown fox jumps over the lazy dog "
|
|
18
|
-
"the quick brown fox jumps over the lazy dog "
|
|
19
|
-
"she sells seashells by the seashore "
|
|
20
|
-
"she sells seashells by the seashore "
|
|
21
|
-
)
|
|
22
|
-
tokenizer = train_bpe(corpus, vocab_size=80, min_frequency=2)
|
|
23
|
-
print(f"vocab size: {tokenizer.vocab_size}") # 78
|
|
24
|
-
print(f"merges learned: {len(tokenizer.merges)}")
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
The first merges combine frequent character pairs:
|
|
28
|
-
|
|
29
|
-
```
|
|
30
|
-
first three merges:
|
|
31
|
-
('h', 'e') -> 'he'
|
|
32
|
-
('he', '</w>') -> 'he</w>'
|
|
33
|
-
('t', 'he</w>') -> 'the</w>'
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
(`</w>` is the end-of-word marker that lets BPE recover word boundaries.)
|
|
37
|
-
|
|
38
|
-
## 2. Encode and decode
|
|
39
|
-
|
|
40
|
-
```python
|
|
41
|
-
text = "the quick brown fox"
|
|
42
|
-
ids = tokenizer.encode(text)
|
|
43
|
-
print(f"ids: {ids}") # [33, 45, 50, 53]
|
|
44
|
-
print(f"tokens: {[tokenizer.id_to_token[i] for i in ids]}")
|
|
45
|
-
# ['the</w>', 'quick</w>', 'brown</w>', 'fox</w>']
|
|
46
|
-
print(f"decoded: {tokenizer.decode(ids)!r}") # 'the quick brown fox'
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
`decode` is a clean round-trip, verify with an assertion in your own code.
|
|
50
|
-
|
|
51
|
-
## 3. Token + positional embeddings
|
|
52
|
-
|
|
53
|
-
The embedding pipeline is two layers: a learned `TokenEmbedding` table plus
|
|
54
|
-
fixed sinusoidal `PositionalEncoding`, summed element-wise via
|
|
55
|
-
`add_positional`.
|
|
56
|
-
|
|
57
|
-
```python
|
|
58
|
-
from cds.nlp import (
|
|
59
|
-
PositionalEncoding,
|
|
60
|
-
TokenEmbedding,
|
|
61
|
-
add_positional,
|
|
62
|
-
)
|
|
63
|
-
|
|
64
|
-
d_model = 16
|
|
65
|
-
table = TokenEmbedding(vocab_size=tokenizer.vocab_size, d_model=d_model)
|
|
66
|
-
pe = PositionalEncoding(max_len=len(ids) + 4, d_model=d_model)
|
|
67
|
-
|
|
68
|
-
tokens = table.forward(ids) # (seq_len, d_model)
|
|
69
|
-
combined = add_positional(tokens, pe) # token + position
|
|
70
|
-
print(f"embedding shape: {len(combined)} x {len(combined[0])}") # 4 x 16
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
The first position's vector is the literal sum of its token and position rows:
|
|
74
|
-
|
|
75
|
-
```
|
|
76
|
-
first token position vector (first 4 dims):
|
|
77
|
-
token: [-0.1726, 0.1360, 0.1900, -0.0182]
|
|
78
|
-
pos: [0.0, 1.0, 0.0, 1.0]
|
|
79
|
-
sum: [-0.1726, 1.1360, 0.1900, 0.9818]
|
|
80
|
-
```
|
|
81
|
-
|
|
82
|
-
## 4. Save and reload
|
|
83
|
-
|
|
84
|
-
A trained tokenizer serializes to JSON and round-trips losslessly:
|
|
85
|
-
|
|
86
|
-
```python
|
|
87
|
-
tokenizer.save("examples/_demo_tokenizer.json")
|
|
88
|
-
loaded = type(tokenizer).load("examples/_demo_tokenizer.json")
|
|
89
|
-
assert loaded.encode(text) == ids
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
## Where this fits
|
|
93
|
-
|
|
94
|
-
The output of `add_positional` is exactly what `multi_head_attention` expects
|
|
95
|
-
(see [`nlp_attention_demo.md`](nlp_attention_demo.md)) and what `MiniGPT`
|
|
96
|
-
consumes (see [`nlp_mini_gpt_demo.md`](nlp_mini_gpt_demo.md)). The whole
|
|
97
|
-
front-to-back Transformer is readable pure Python.
|
|
98
|
-
|
|
99
|
-
Run the full demo:
|
|
100
|
-
|
|
101
|
-
```bash
|
|
102
|
-
python examples/nlp_bpe_demo.py
|
|
103
|
-
```
|
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
# MiniGPT Training Tutorial
|
|
2
|
-
|
|
3
|
-
This is the capstone of the `cds.nlp` stack: a tiny **MiniGPT** (one causal
|
|
4
|
-
Transformer block, `d_model=32`) trained from scratch on a Shakespeare excerpt
|
|
5
|
-
using a scalar autograd engine and an Adam optimizer. Pure Python end to end.
|
|
6
|
-
|
|
7
|
-
## 1. The full pipeline
|
|
8
|
-
|
|
9
|
-
The demo runs four steps:
|
|
10
|
-
|
|
11
|
-
1. **Encode** the corpus to token ids via the bundled Shakespeare text.
|
|
12
|
-
2. **Build** the model: embedding + positional encoding + one causal
|
|
13
|
-
multi-head-attention block + feed-forward + output head.
|
|
14
|
-
3. **Train** by sliding a window over the corpus, predicting the next
|
|
15
|
-
character, and updating with Adam.
|
|
16
|
-
4. **Sample** text from the trained model.
|
|
17
|
-
|
|
18
|
-
```python
|
|
19
|
-
from cds.nlp.autograd.tensor import Tensor
|
|
20
|
-
from cds.nlp.data import TEXT, decode, encode, vocab_size
|
|
21
|
-
from cds.nlp.model import MiniGPT
|
|
22
|
-
from cds.nlp.optim import Adam
|
|
23
|
-
from cds.nlp.training import train_step
|
|
24
|
-
|
|
25
|
-
ids = encode(TEXT)
|
|
26
|
-
print(f"corpus: {len(ids)} chars, vocab_size={vocab_size}")
|
|
27
|
-
|
|
28
|
-
model = MiniGPT(
|
|
29
|
-
vocab_size=vocab_size,
|
|
30
|
-
d_model=32,
|
|
31
|
-
n_heads=2,
|
|
32
|
-
d_ff=64,
|
|
33
|
-
max_len=32,
|
|
34
|
-
seed=42,
|
|
35
|
-
)
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
## 2. The autograd engine
|
|
39
|
-
|
|
40
|
-
Unlike the float-matrix math in the other nlp demos, MiniGPT's parameters are
|
|
41
|
-
`Tensor` objects from `cds.nlp.autograd`, each op records its inputs on a tape
|
|
42
|
-
so `backward()` can compute gradients automatically. This is the same design
|
|
43
|
-
idea as micrograd / tinygrad, kept minimal so the source stays readable.
|
|
44
|
-
|
|
45
|
-
## 3. The training loop
|
|
46
|
-
|
|
47
|
-
The loop is explicit so you can see exactly what each step does:
|
|
48
|
-
|
|
49
|
-
```python
|
|
50
|
-
T = 24
|
|
51
|
-
params: list[Tensor] = model.parameters() # type: ignore[assignment]
|
|
52
|
-
optimiser = Adam(params=params, lr=0.005)
|
|
53
|
-
n_steps = 200
|
|
54
|
-
|
|
55
|
-
import random
|
|
56
|
-
|
|
57
|
-
losses: list[float] = []
|
|
58
|
-
for step in range(n_steps):
|
|
59
|
-
start = random.randint(0, max(0, len(ids) - T - 1))
|
|
60
|
-
x = ids[start : start + T]
|
|
61
|
-
y = ids[start + T]
|
|
62
|
-
loss = train_step(model.forward, x, y, optimiser)
|
|
63
|
-
losses.append(loss)
|
|
64
|
-
if step % 20 == 0:
|
|
65
|
-
avg = sum(losses[-20:]) / min(20, len(losses))
|
|
66
|
-
print(f" step {step:3d}: loss={avg:.4f}")
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
The loss is the cross-entropy of the next-character prediction. Over 200 steps
|
|
70
|
-
the moving-average loss falls steadily as the model learns character-level
|
|
71
|
-
statistics of the corpus.
|
|
72
|
-
|
|
73
|
-
> Note: `params: list[Tensor] = model.parameters()` is annotated with
|
|
74
|
-
> `# type: ignore[assignment]` because `parameters()` returns
|
|
75
|
-
> `list[Parameter]` (a `Tensor` subclass) and Python lists are invariant. The
|
|
76
|
-
> runtime assignment is sound; the cast only satisfies strict mypy.
|
|
77
|
-
|
|
78
|
-
## 4. Sampling
|
|
79
|
-
|
|
80
|
-
After training, seed the model with a prompt and let it generate one token at a
|
|
81
|
-
time, feeding each prediction back in (autoregressive decoding):
|
|
82
|
-
|
|
83
|
-
```python
|
|
84
|
-
prompt = encode("All the ")
|
|
85
|
-
out = model.sample(prompt, n_tokens=120)
|
|
86
|
-
print(decode(out))
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
The output won't be coherent Shakespeare, 200 steps on a tiny corpus is a
|
|
90
|
-
demonstration, not a real model, but it will reflect learned character
|
|
91
|
-
frequencies and common bigrams, which is the whole point: you can watch a
|
|
92
|
-
language model come into being from first principles.
|
|
93
|
-
|
|
94
|
-
## Why it matters
|
|
95
|
-
|
|
96
|
-
Most GPT tutorials hide the mechanics behind a framework. Here, the entire path,
|
|
97
|
-
BPE-free char encoding, positional encoding, causal multi-head attention,
|
|
98
|
-
feed-forward, layernorm, autograd, Adam, sampling, is open Python you can
|
|
99
|
-
read, modify, and instrument. Start from
|
|
100
|
-
[`nlp_bpe_demo.md`](nlp_bpe_demo.md) and [`nlp_attention_demo.md`](nlp_attention_demo.md)
|
|
101
|
-
for the building blocks.
|
|
102
|
-
|
|
103
|
-
> Note: the full demo trains for 200 steps and takes about a minute. Run it
|
|
104
|
-
> when you don't mind waiting.
|
|
105
|
-
|
|
106
|
-
Run the full demo:
|
|
107
|
-
|
|
108
|
-
```bash
|
|
109
|
-
python examples/nlp_mini_gpt_demo.py
|
|
110
|
-
```
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
# Visualising NLP Internals
|
|
2
|
-
|
|
3
|
-
The `cds.nlp.viz` module renders the three things a learner most wants to
|
|
4
|
-
*see* when reading about transformers: attention, embeddings, and the
|
|
5
|
-
training-loss curve, as ASCII, so you need no plotting backend. Every
|
|
6
|
-
renderer returns a `str`, which means they compose under `print()`, log
|
|
7
|
-
cleanly, and are trivially testable.
|
|
8
|
-
|
|
9
|
-
## 1. The training-loss curve
|
|
10
|
-
|
|
11
|
-
```python
|
|
12
|
-
from cds.nlp import render_training_curve
|
|
13
|
-
|
|
14
|
-
losses = [3.5, 3.1, 2.8, 2.55, 2.3, 2.1, 1.95, 1.82, 1.7, 1.6]
|
|
15
|
-
print(render_training_curve(losses, width=50, height=10))
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
The curve is min-max normalised to the canvas. A single point or an
|
|
19
|
-
all-equal series is handled safely (no divide-by-zero); narrow widths
|
|
20
|
-
(`width < 10`) are also safe, the x-axis step label right-aligns rather
|
|
21
|
-
than raising a format error.
|
|
22
|
-
|
|
23
|
-
## 2. The attention heatmap
|
|
24
|
-
|
|
25
|
-
```python
|
|
26
|
-
from cds.nlp import render_attention_heatmap
|
|
27
|
-
|
|
28
|
-
attn = [[0.7, 0.2, 0.1], [0.1, 0.8, 0.1], [0.05, 0.15, 0.8]]
|
|
29
|
-
tokens = ["the", "cat", "sat"]
|
|
30
|
-
print(render_attention_heatmap(attn, tokens, tokens))
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
Weights are normalised across the whole matrix per render, then mapped to
|
|
34
|
-
nine ASCII shades (`' '` → `'#'`). The diagonal of a causal or
|
|
35
|
-
identity-style attention pattern lights up as the darkest cells. Shape
|
|
36
|
-
mismatches between the matrix, the row tokens, and the column tokens each
|
|
37
|
-
raise a labelled `ValueError` so a wrong call is easy to spot.
|
|
38
|
-
|
|
39
|
-
## 3. The embedding projection
|
|
40
|
-
|
|
41
|
-
```python
|
|
42
|
-
from cds.nlp import render_embedding_projection
|
|
43
|
-
|
|
44
|
-
# Six 3-D embedding vectors; imagine six vocabulary entries.
|
|
45
|
-
emb = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [0, 1, 1], [1, 0, 1]]
|
|
46
|
-
labels = ["a", "b", "c", "ab", "bc", "ac"]
|
|
47
|
-
print(render_embedding_projection(emb, labels=labels, top_n=6))
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
The projection is **real PCA**, not a placeholder: the covariance matrix of
|
|
51
|
-
the embeddings is built in pure Python, then
|
|
52
|
-
[`cds.math_utils.linalg.power_iteration`](../api.md#cds.math_utils.power_iteration)
|
|
53
|
-
recovers the top-2 eigenvectors (the second via deflation). This is the
|
|
54
|
-
project's signature "slow but honest" trade-off, the math is exactly what
|
|
55
|
-
`sklearn.decomposition.PCA` does, just without the BLAS.
|
|
56
|
-
|
|
57
|
-
`top_n` keeps large vocabularies readable by plotting only the
|
|
58
|
-
highest-variance points along PC1 (pass `top_n=0` or a negative value to
|
|
59
|
-
render every point).
|
|
60
|
-
|
|
61
|
-
## Why ASCII?
|
|
62
|
-
|
|
63
|
-
Three reasons, in priority order:
|
|
64
|
-
|
|
65
|
-
1. **Zero-dependency.** No matplotlib import on the default path keeps
|
|
66
|
-
`cds` installable with nothing but the standard library.
|
|
67
|
-
2. **Composability.** A `str` return value logs, prints, and diffs in a
|
|
68
|
-
test exactly like any other value.
|
|
69
|
-
3. **Teaching clarity.** The renderer source is short enough to read in
|
|
70
|
-
one sitting, which is the point of the whole `cds.nlp` track.
|
|
71
|
-
|
|
72
|
-
For publication-quality plots, export the matrices
|
|
73
|
-
(`attn_weights`, the `_pca_2d` result, `losses`) and plot them with your
|
|
74
|
-
own toolchain, the data path is the same. The runnable demo at
|
|
75
|
-
[`examples/nlp_viz_demo.py`](https://github.com/Furox-Art/scientific-computing-system/blob/main/examples/nlp_viz_demo.py)
|
|
76
|
-
wires all three renderers to a tiny live tokenizer + embedding pass.
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
# Numerical Integration Tutorial
|
|
2
|
-
|
|
3
|
-
`cds.numerical_integration` provides deterministic quadrature rules. A canonical test: `∫_0^1 e^x dx = e - 1`.
|
|
4
|
-
|
|
5
|
-
## 1. Newton–Cotes Rules
|
|
6
|
-
|
|
7
|
-
```python
|
|
8
|
-
import math
|
|
9
|
-
from cds.numerical_integration import trapezoid, simpson, simpson_38
|
|
10
|
-
|
|
11
|
-
f = math.exp
|
|
12
|
-
print(trapezoid(f, 0, 1, 1000)) # O(h^2)
|
|
13
|
-
print(simpson(f, 0, 1, 100)) # O(h^4)
|
|
14
|
-
print(simpson_38(f, 0, 1, 99)) # 3/8 variant
|
|
15
|
-
```
|
|
16
|
-
|
|
17
|
-
## 2. Higher-Order & Adaptive
|
|
18
|
-
|
|
19
|
-
```python
|
|
20
|
-
from cds.numerical_integration import gaussian_quadrature, romberg, adaptive_simpson
|
|
21
|
-
|
|
22
|
-
print(gaussian_quadrature(f, 0, 1, 8).value) # ~1e-16 error
|
|
23
|
-
print(romberg(f, 0, 1).value) # Richardson extrapolation
|
|
24
|
-
print(adaptive_simpson(f, 0, 1).value) # tolerance-driven bisection
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
**Why it matters:** you can watch error drop from `1e-7` (trapezoid) to `1e-16` (Gauss-Legendre) on the same problem, a clear lesson in quadrature convergence.
|
|
28
|
-
|
|
29
|
-
## 3. 2-D Tensor-Product Quadrature
|
|
30
|
-
|
|
31
|
-
Both `simpson_2d` and `gaussian_quadrature_2d` integrate a bivariate
|
|
32
|
-
function over a rectangle `[ax, bx] × [ay, by]` by taking the tensor product
|
|
33
|
-
of a 1-D rule in each axis.
|
|
34
|
-
|
|
35
|
-
```python
|
|
36
|
-
import math
|
|
37
|
-
from cds.numerical_integration import simpson_2d, gaussian_quadrature_2d
|
|
38
|
-
|
|
39
|
-
# ∬_{[0,1]^2} e^{x+y} dx dy = (e-1)^2 ≈ 2.9525
|
|
40
|
-
f = lambda x, y: math.exp(x + y)
|
|
41
|
-
exact = (math.e - 1) ** 2
|
|
42
|
-
|
|
43
|
-
# Composite Simpson 1/3 in each axis — O(h_x^4 + h_y^4).
|
|
44
|
-
print(simpson_2d(f, 0, 1, 0, 1, 50, 50)) # ~2.9525
|
|
45
|
-
|
|
46
|
-
# Tensor-product Gauss-Legendre: n nodes per axis integrate polynomials
|
|
47
|
-
# up to degree 2n-1 in *each* variable exactly. 5 nodes is far past exact
|
|
48
|
-
# for the smooth exponential, so it lands essentially on the closed form.
|
|
49
|
-
print(gaussian_quadrature_2d(f, 0, 1, 0, 1, 5)) # ~2.9525
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
**Exactness check.** `gaussian_quadrature_2d` with `n=3` integrates
|
|
53
|
-
`x^5 · y^5` over `[0,1]^2` to machine precision, since each axis is exact to
|
|
54
|
-
degree `2n-1 = 5`:
|
|
55
|
-
|
|
56
|
-
```python
|
|
57
|
-
# Analytic value: (1/6)·(1/6) = 1/36 ≈ 0.027778
|
|
58
|
-
val = gaussian_quadrature_2d(lambda x, y: x**5 * y**5, 0, 1, 0, 1, 3)
|
|
59
|
-
assert abs(val - 1 / 36) < 1e-12
|
|
60
|
-
```
|
|
61
|
-
|
|
62
|
-
**Reversed limits** are honoured consistently: flipping one axis flips the
|
|
63
|
-
sign once, flipping both flips it twice (net unchanged), exactly as in 1-D.
|
|
64
|
-
|
|
65
|
-
Run the full demo with `python examples/numerical_integration_demo.py`.
|