Run this model with HF Jobs
Run Frankenstein-Labs/cortex.6.sol on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/Frankenstein-Labs/cortex.6.sol. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Frankenstein-Labs/cortex.6.sol on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/Frankenstein-Labs/cortex.6.sol. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/Frankenstein-Labs/cortex.6.sol. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use Frankenstein-Labs/cortex.6.sol with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Frankenstein-Labs/cortex.6.sol with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Frankenstein-Labs/cortex.6.sol")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("Frankenstein-Labs/cortex.6.sol") model = AutoModelForCausalLM.from_pretrained("Frankenstein-Labs/cortex.6.sol", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Frankenstein-Labs/cortex.6.sol with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Frankenstein-Labs/cortex.6.sol" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Frankenstein-Labs/cortex.6.sol", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Frankenstein-Labs/cortex.6.sol
- SGLang
How to use Frankenstein-Labs/cortex.6.sol with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Frankenstein-Labs/cortex.6.sol" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Frankenstein-Labs/cortex.6.sol", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Frankenstein-Labs/cortex.6.sol" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Frankenstein-Labs/cortex.6.sol", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Frankenstein-Labs/cortex.6.sol with Docker Model Runner:
docker model run hf.co/Frankenstein-Labs/cortex.6.sol
feat(cortex): add CORTEX training pipeline and model audit
Browse filesFrankenstein-Labs' own CORTEX weights need a training pipeline. This adds one,
strictly separate from the distributed 1.65T checkpoint, which no script here
reads or modifies.
Pipeline:
- model/cortex_model.py decoder-only Transformer (RMSNorm, RoPE, GQA, SwiGLU)
- model/init.py weight init and checkpoint I/O
- tokenizer/ loads the shipped tokenizer, validates vocab_size
- training/train.py training loop with a dataset licence gate
- datasets/ code datasets with declared source and licence
- evaluation/evaluate.py loss, perplexity, generation
- configs/cortex/ cortex-dev-1, ~174,803,712 params
Correctness details found while building it:
- safetensors refuses to save storage-sharing keys, which tied embeddings are.
The tied matrix is stored once, aliased in provenance.json, and re-expanded
on load, so checkpoints stay lossless.
- Cross-entropy over full 129280-wide fp32 logits restarted the sandbox, so the
softmax is computed in 8192-row chunks.
- The tokenizer exposes 129283 counters but 129280 unique ids (ids 0/1/2 appear
in both the BPE vocab and the added tokens). Tests compare unique ids.
Verified: 28 pipeline tests pass, including an overfit test asserting loss falls.
A 20-step CPU run on real CodeAlpaca data drops loss 11.31 -> 9.01. A checkpoint
is written with a SHA-256 manifest, and a corrupted one is rejected on load.
Not verified: no long training run (4 CPU cores, no GPU), and no code-generation
quality is claimed. Evaluation at step 6 reports perplexity ~67k and 0 exact
matches, as measured.
Provenance is unchanged: the 66 shards are untouched, base_model stays null in
CORTEX checkpoints, and the MIT attribution for the distributed weights remains.
docs/architecture-modele.fr.md records the measured architecture.
Co-authored-by: openhands <openhands@all-hands.dev>
Files changed (26)
- .gitignore+3-1
- AGENTS.md+44-6
- README.md+54
- checkpoints/README.mdAdded+40
- configs/cortex/cortex-dev-1.jsonAdded+79
- datasets/README.mdAdded+73
- datasets/build.pyAdded+148
- datasets/cortex-code-eval.jsonlAdded
- datasets/cortex-code-eval.meta.jsonAdded+18
- datasets/cortex-code-sft.jsonlAdded+200
- datasets/cortex-code-sft.meta.jsonAdded+18
- datasets/cortex-code-tests.jsonlAdded+200
- datasets/cortex-code-tests.meta.jsonAdded+18
- datasets/registry.jsonAdded+97
- docs/architecture-modele.fr.mdAdded+272
- docs/pipeline-cortex.fr.mdAdded+113
- evaluation/README.mdAdded+41
- evaluation/evaluate.pyAdded+123
- model/README.mdAdded+67
- model/cortex_model.pyAdded+335
- model/init.pyAdded+214
- tests/test_cortex_pipeline.pyAdded+322
- tokenizer/README.mdAdded+53
- tokenizer/cortex_tokenizer.pyAdded+67
- training/README.mdAdded+60
- training/train.pyAdded+237
3 unmodified lines456783 unmodified lines.ipynb_checkpoints/# Stage-1 projector checkpoints are reproducible artefacts, not source.checkpoints/*.pt3 unmodified lines456789103 unmodified lines.ipynb_checkpoints/# Stage-1 projector checkpoints are reproducible artefacts, not source.# The CORTEX training checkpoints are also artefacts; only their README is tracked.checkpoints/*!checkpoints/README.md*.pt
4 unmodified lines567891011121388 unmodified lines1021031041051061071081091101111121131141151161174 unmodified lines## Repository state- `Frankenstein-Labs/Cortex-ai` HEAD = `f7ae039134bdb7a6acac688ddc67a523dd4eaf17`("docs(cortex): center public presentation on CORTEX and Frankenstein-Labs"), branch `main`,no tags. Earlier state was `f019291` ("feat: add founder behavioral charter").- The repo is a **redistribution** of `deepseek-ai/DeepSeek-V4-Pro-0813`.- The model card was rewritten to present **CORTEX** (developer: Frankenstein-Labs) as theproduct. The base model is named only in the frontmatter `base_model` key, in the technical88 unmodified lines`(1, 204, 1000)`, and embeddings change with image content (red-vs-blue delta 0.46). It does**not** yet work with the real 1.65 T core.## Test commands```bashPYTHONPATH=/workspace/project python3 -m pytest tests/ -q # 14 passed, 1 skippedPYTHONPATH=/workspace/project/encoding python3 -m pytest encoding/test_encoding_dsv4.py -q # 4 testsCORTEX_REAL_VISION_TEST=1 python3 -m pytest tests/ -q -k real # real SigLIP + pythiapython tools/shard_integrity.py --from-worktree --out /tmp/after.json # 66 shard hashes```Requires `torch` (CPU wheel), `torchvision`, `pillow`, `transformers`, and `datasets` for training.## Stage-1 projector training (implemented and verified)4 unmodified lines56789101112131488 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541554 unmodified lines## Repository state- `Frankenstein-Labs/Cortex-ai` HEAD = `e1985aeed6feaf79bc0a224bc8d11ded0813e7e4`("docs(cortex): trim redundant model card tags"), branch `main`, no tags.History: `f019291` (founder charter) -> `f7ae039` (CORTEX-centered model card) ->`8fd8333` (AGENTS.md) -> `e1985ae` (tag trim).- The repo is a **redistribution** of `deepseek-ai/DeepSeek-V4-Pro-0813`.- The model card was rewritten to present **CORTEX** (developer: Frankenstein-Labs) as theproduct. The base model is named only in the frontmatter `base_model` key, in the technical88 unmodified lines`(1, 204, 1000)`, and embeddings change with image content (red-vs-blue delta 0.46). It does**not** yet work with the real 1.65 T core.## CORTEX training pipeline (implemented and verified)Frankenstein-Labs' own weights are built by `model/`, `tokenizer/`, `training/`, `datasets/`,`evaluation/` and `configs/cortex/`. This is **strictly separate** from the distributedcheckpoint: no pipeline script reads or writes the 66 shards.- `configs/cortex/cortex-dev-1.json` = `cortex-dev-1`, ~**174,803,712** params (12 layers,hidden 768, 12/4 heads, ctx 2048, fp32, tied embeddings, CORTEX vocab 129280).`CortexConfig.parameter_breakdown()` and `count_parameters()` must agree — a test asserts it.- **The training loop demonstrably learns.** On real CodeAlpaca data over 20 CPU steps:loss 11.3117 -> 10.4505 -> 9.8508 -> 9.0094. An overfit test (`...reduces_loss_on_a_tiny_corpus`)asserts loss falls, so a regression in the loop is caught by CI.- Checkpoints are directories: `config.json`, `weights.safetensors`, `provenance.json`,`manifest.json` (+ `optimizer.pt`). `load_cortex_checkpoint()` verifies size + SHA-256 andrejects a corrupted file.- `provenance.json` always carries `base_model: null` for these weights, with a note. **Do notpopulate `base_model` unless the weights really derive from another model.** It is a factualfield, not marketing.- Dataset licence gate: `assert_dataset_usable()` refuses any dataset not declared in`datasets/registry.json`, or whose licence is absent/`unknown`/`none`/`proprietary`.`the-stack-dedup` and `starcoderdata` are declared **rejected** (licence `other`, gated).- Tokenizer reuse is safe: 128000 BPE + 1283 added = 129283 counters, but ids 0/1/2 are in bothsets, so **unique ids = 129280 = `vocab_size`**. Always compare unique ids, never raw counters.Gotchas found while building this:- `safetensors` **refuses to save two keys sharing storage**, which tied embeddings do. Fixed in`model/init.py::_split_tied_tensors`: one copy is written, the alias is recorded in`provenance.json["tied_tensors"]`, and `load_cortex_checkpoint()` re-expands it. Saving the raw`state_dict()` raises `RuntimeError: Some tensors share memory`.- Computing cross-entropy over the full 129280-wide logits in fp32 at batch 2x512 (~0.5 GB) isenough to **restart this sandbox**. `CortexForCausalLM._loss` chunks the softmax at 8192 rows.- Full training has **not** been run: 4 CPU cores, ~15 GiB RAM, no GPU. Evaluation at step 6 showsperplexity ~67k and 0 exact matches on HumanEval — reported as measured, never dressed up.## Test commands```bashPYTHONPATH=/workspace/project python3 -m pytest tests/ -q --ignore=tests/test_api.py # 97 passed, 1 skippedPYTHONPATH=/workspace/project python3 -m pytest tests/test_cortex_pipeline.py -q # 28 passedPYTHONPATH=/workspace/project/encoding python3 -m pytest encoding/test_encoding_dsv4.py -q # 4 testsCORTEX_REAL_VISION_TEST=1 python3 -m pytest tests/ -q -k real # real SigLIP + pythiapython tools/shard_integrity.py --from-worktree --out /tmp/after.json # 66 shard hashes```Requires `torch` (CPU wheel), `torchvision`, `pillow`, `transformers`, and `datasets` for training.`tests/test_api.py` needs `fastapi`, which is **not installed** in this image; ignore that file.## Stage-1 projector training (implemented and verified)
126 unmodified lines12712812913013113295 unmodified lines228229230231232233234235236237238239126 unmodified lines---## Technical overviewCORTEX runs on a very large mixture-of-experts model designed for long reasoning and code95 unmodified lines## Roadmap- **CORTEX Engine** — agent, task and tool orchestration.- **CORTEX IDE** — an AI-native development environment.- **CORTEX Cloud** — assisted cloud development workflows.- **Complete French documentation** — guides, tutorials and examples.- **Vision layer** — encoder selection, projector training, end-to-end validation.---## Disclaimer126 unmodified lines12712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817995 unmodified lines275276277278279280281282283284285286287288289290291292293126 unmodified lines---## Building CORTEX weightsFrankenstein-Labs is building its **own** CORTEX weights, in the open, in this repository.| Component | Role | State ||---|---|---|| `model/` | CORTEX architecture (RMSNorm, RoPE, GQA, SwiGLU) and checkpoint I/O | Working, tested || `tokenizer/` | CORTEX tokenizer, validated against `vocab_size` | Working, tested || `training/` | Training loop, with a licence gate on every dataset | Working, tested || `datasets/` | Code datasets with declared source, licence and SHA-256 | Working || `evaluation/` | Loss, perplexity, generation | Working || `configs/cortex/` | `cortex-dev-1`: a ~175 M-parameter development model | Working |The pipeline is **completely separate** from the distributed checkpoint. It never reads ormodifies the 66 shards; it initialises new weights from scratch and trains them.```bashpip install torch safetensors tokenizers transformers numpy pytestpython datasets/build.py --all --limit 200 # fetch datasetsPYTHONPATH=. python3 -m pytest tests/test_cortex_pipeline.py -q # 28 testsPYTHONPATH=. python3 -c "from training.train import trainprint(train('configs/cortex/cortex-dev-1.json', ['cortex-code-sft'],out_dir='checkpoints/dev', max_steps=100, device='cpu', progress=True))"```### What is actually true about this pipeline**Measured.** The test suite passes. A short CPU run on real code data (CodeAlpaca) reduces theloss steadily — 11.31 → 10.45 → 9.85 → 9.01 over 20 steps — so the loop genuinely learns. Acheckpoint is written with a manifest, and a corrupted checkpoint is rejected on load.**Not measured.** No long training run has been completed: this sandbox has 4 CPU cores, ~15 GiBof RAM and no GPU. No code-generation quality is claimed. A ~175 M-parameter model trained for afew hundred steps does not write reliable code, and the evaluation reports exactly that(perplexity in the tens of thousands, zero exact matches at step 6).`base_model` in a CORTEX checkpoint's `provenance.json` stays `null` until weights genuinelyderive from another model. It is not a marketing field.See [`docs/pipeline-cortex.fr.md`](docs/pipeline-cortex.fr.md) for the full picture.---## Technical overviewCORTEX runs on a very large mixture-of-experts model designed for long reasoning and code95 unmodified lines## Roadmap- **CORTEX training pipeline** — train the development model to convergence on GPU and publishthe real curves. In progress: the pipeline runs and learns, the long run has not happened.- **Execution-based evaluation** — `pass@k` on MBPP in a sandbox. Not implemented.- **CORTEX Engine** — agent, task and tool orchestration.- **CORTEX IDE** — an AI-native development environment.- **CORTEX Cloud** — assisted cloud development workflows.- **Complete French documentation** — guides, tutorials and examples.- **Vision layer** — encoder selection, projector training, end-to-end validation.The public presentation of CORTEX will only claim trained-by-Frankenstein-Labs weights once suchweights exist and have been evaluated. Until then, this repository is honest about what it holds:a redistribution of an existing model, plus a training pipeline under construction.---## Disclaimer
12345678910111213141516171819202122232425262728293031323334353637383940# CORTEX — checkpoints
Ce dossier contient les checkpoints **produits par Frankenstein-Labs**.
Rien n'y est versionné : les checkpoints sont des artefacts reproductibles, pas du code.`.gitignore` exclut `*.pt`, `*.safetensors` et le contenu de ce dossier.
## Structure d'un checkpoint
```textcheckpoints/dev/ step-500/ config.json hyper-paramètres du modèle weights.safetensors provenance.json développeur, base_model, datasets, configuration manifest.json tailles et SHA-256 de chaque fichier final/ ...```
## Vérification
```pythonfrom model.init import load_cortex_checkpoint
model, config, provenance = load_cortex_checkpoint("checkpoints/dev/final")print(config.model_name, provenance["step"], provenance["parameter_count"])```
`load_cortex_checkpoint()` recalcule le SHA-256 de chaque fichier listé dans le manifesteet refuse le checkpoint si un fichier manque, change de taille ou est corrompu.
## Distinction à conserver
Un checkpoint de ce dossier est un modèle **entraîné par Frankenstein-Labs**. Il n'aaucun lien de dérivation avec les 66 shards distribués dans ce dépôt, qui proviennent deDeepSeek-AI et restent inchangés. Le champ `base_model` de `provenance.json` vaut `null`tant que c'est le cas.
Voir `docs/pipeline-cortex.fr.md` pour l'état réel du pipeline.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879{ "model_name": "cortex-dev-1", "status": "development-config-not-trained", "_comment": [ "CORTEX dev-scale training configuration.", "This describes a model Frankenstein-Labs can actually TRAIN on realistic hardware.", "It does NOT describe the distributed checkpoint in this repository, which is a", "1.65T-parameter redistribution and is untouched by this pipeline.", "Any checkpoint produced from this config is a new, separately trained model." ],
"architecture": "cortex_dense_decoder", "hidden_size": 768, "num_hidden_layers": 12, "num_attention_heads": 12, "num_key_value_heads": 4, "intermediate_size": 2048, "hidden_act": "silu", "max_position_embeddings": 2048, "rope_theta": 10000.0, "rms_norm_eps": 1e-05, "attention_bias": false, "attention_dropout": 0.0, "tie_word_embeddings": true, "initializer_range": 0.02, "torch_dtype": "float32", "use_cache": true,
"vocab_size": 129280, "bos_token_id": 0, "eos_token_id": 1, "pad_token_id": 2,
"tokenizer_source": { "repo": "Frankenstein-Labs/Cortex-ai", "file": "tokenizer.json", "license": "MIT", "note": "Reused as-is from the distributed repository. The tokenizer is not modified." },
"training": { "precision": "float32", "micro_batch_size": 2, "gradient_accumulation_steps": 8, "effective_batch_size": 16, "learning_rate": 0.0003, "min_learning_rate": 0.00003, "weight_decay": 0.1, "beta1": 0.9, "beta2": 0.95, "grad_clip": 1.0, "warmup_steps": 100, "max_steps": 20000, "lr_schedule": "cosine", "seed": 1337, "log_every": 10, "eval_every": 500, "save_every": 1000, "sequence_length": 512 },
"hardware_expectation": { "minimum": "1 CPU core, ~2 GiB RAM, runs but very slowly", "recommended": "1 GPU with >= 8 GiB VRAM", "verified_on": "4 CPU cores, ~15 GiB RAM, no GPU", "note": "Smoke-tested on CPU. Full training is not claimed to have been run." },
"provenance": { "developer": "Frankenstein-Labs", "weights": "randomly initialised by this pipeline, then trained by Frankenstein-Labs", "base_model": null, "base_model_note": [ "Deliberately null: no parent model applies to weights produced from this config.", "This field must stay null unless the weights are in fact derived from another model." ], "license": "mit" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273# CORTEX — datasets
Datasets de code pour l'entraînement de CORTEX, avec traçabilité complète des sources etdes licences.
| Fichier | Rôle ||---|---|| `registry.json` | déclaration des sources, licences et jeux refusés || `build.py` | récupération reproductible des échantillons || `<id>.jsonl` | les enregistrements || `<id>.meta.json` | provenance : source, licence, compteurs, SHA-256 |
## Jeux retenus
| id | Source | Licence | Usage ||---|---|---|---|| `cortex-code-sft` | `sahil2801/CodeAlpaca-20k` | CC BY 4.0 | entraînement || `cortex-code-tests` | `google-research-datasets/mbpp` | CC BY 4.0 | entraînement / évaluation || `cortex-code-eval` | `openai/openai_humaneval` | MIT | **évaluation seule** |
Les licences ci-dessus ont été lues depuis l'API du Hub, pas reprises de mémoire.
### Attributions
- **CodeAlpaca-20k** — CC BY 4.0. Citer le dépôt `sahil2801/CodeAlpaca-20k`.- **MBPP** — Google Research, CC BY 4.0. Citer `google-research-datasets/mbpp`.- **HumanEval** — OpenAI, licence MIT. Citer `openai/openai_humaneval`.
## Jeux refusés
Ces sources existent et sont populaires, mais ne peuvent pas entrer dans CORTEX :
| Source | Licence déclarée | Motif du refus ||---|---|---|| `bigcode/the-stack-dedup` | `other` | accès sous conditions, termes non vérifiables || `bigcode/starcoderdata` | `other` | accès sous conditions, licences par fichier non déclarées || `codeparrot/codeparrot-clean` | aucune | aucun octroi de licence || `codeparrot/github-code` | `other` | termes non vérifiables || `iamtarun/python_code_instructions_18k_alpaca` | aucune | aucun octroi de licence |
`the-stack-dedup` et `starcoderdata` sont les sources les plus utilisées pour entraîner desmodèles de code. Elles restent hors de ce pipeline tant que leurs termes ne peuvent pasêtre vérifiés depuis les métadonnées du Hub.
## Traçabilité
Chaque `<id>.meta.json` enregistre :
```json{ "source": "sahil2801/CodeAlpaca-20k", "license": "cc-by-4.0", "license_url": "https://huggingface.co/datasets/sahil2801/CodeAlpaca-20k", "attribution": "...", "rows_fetched": 200, "records_written": 200, "jsonl_sha256": "...", "fetched_via": "https://datasets-server.huggingface.co/rows"}```
Un test vérifie que le SHA-256 de chaque `.jsonl` correspond à celui de son `.meta.json`.
## Utilisation
```bashpython datasets/build.py --dataset cortex-code-sft --limit 200python datasets/build.py --all --limit 200```
Les échantillons sont volontairement petits (quelques centaines de lignes) pour que lepipeline soit exécutable et vérifiable sur une machine de développement. Ce ne sont pasdes corpus d'entraînement à l'échelle : voir `docs/pipeline-cortex.fr.md`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Build CORTEX code datasets from declared sources, with license traceability.
Every dataset CORTEX trains on must be declared in ``registry.json`` with its originand license. This script fetches a small, reproducible sample from each source andwrites two files per dataset:
* ``datasets/<id>.jsonl`` the records * ``datasets/<id>.meta.json`` provenance: source, license, counts, SHA-256
It never touches the distributed model checkpoint.
Usage::
python datasets/build.py --dataset cortex-code-sft python datasets/build.py --all --limit 200"""
from __future__ import annotations
import argparseimport hashlibimport jsonimport urllib.parseimport urllib.requestfrom pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parentDATASETS_DIR = REPO_ROOT / "datasets"
__all__ = ["build_dataset", "load_registry"]
def load_registry(path: str | Path | None = None) -> dict: path = Path(path) if path else DATASETS_DIR / "registry.json" return json.loads(path.read_text(encoding="utf-8"))
def _rows(dataset: str, config: str, split: str, offset: int, length: int) -> dict: query = urllib.parse.urlencode( {"dataset": dataset, "config": config, "split": split, "offset": offset, "length": length} ) req = urllib.request.Request( f"https://datasets-server.huggingface.co/rows?{query}", headers={"User-Agent": "cortex-dataset-builder"}, ) with urllib.request.urlopen(req, timeout=120) as r: return json.load(r)
def _fetch_all(dataset: str, config: str, split: str, limit: int, page: int = 100) -> list[dict]: out, offset = [], 0 while len(out) < limit: payload = _rows(dataset, config, split, offset, min(page, limit - len(out))) batch = [row["row"] for row in payload.get("rows", [])] if not batch: break out.extend(batch) offset += len(batch) return out
def _sha256_text(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest()
def _record_from_source(entry: dict, row: dict) -> dict | None: """Map a source row to a CORTEX training record using the entry's field map.""" fields = entry["fields"] if entry["record_type"] != "code-sft": return None prompt = row.get(fields["prompt"]) or "" completion = row.get(fields["completion"]) or "" if entry.get("instruction_field"): prompt = row.get(entry["instruction_field"]) or "" extra = row.get(entry.get("input_field", "")) or "" if extra: prompt = f"{prompt}\n{extra}".strip() if not prompt or not completion: return None source_id = row.get(entry["id_field"]) if entry.get("id_field") else None return { "text": f"### Instruction\n{prompt}\n\n### Response\n{completion}", "source_id": str(source_id) if source_id is not None else "", }
def build_dataset(entry: dict, limit: int) -> dict: print(f"[{entry['id']}] fetching {limit} rows from {entry['source']} ({entry['split']})") rows = _fetch_all(entry["source"], entry["config"], entry["split"], limit)
records = [r for r in (_record_from_source(entry, row) for row in rows) if r is not None] if not records: raise ValueError(f"[{entry['id']}] produced no usable records")
jsonl_path = DATASETS_DIR / f"{entry['id']}.jsonl" body = "\n".join(json.dumps(r, ensure_ascii=False) for r in records) + "\n" jsonl_path.write_text(body, encoding="utf-8")
meta = { "id": entry["id"], "source": entry["source"], "config": entry["config"], "split": entry["split"], "origin": entry["origin"], "license": entry["license"], "license_url": entry["license_url"], "redistribution": entry["redistribution"], "attribution": entry.get("attribution"), "record_type": entry["record_type"], "rows_fetched": len(rows), "records_written": len(records), "jsonl_sha256": _sha256_text(body), "jsonl_bytes": len(body.encode("utf-8")), "note": entry.get("note"), "fetched_via": "https://datasets-server.huggingface.co/rows", } (DATASETS_DIR / f"{entry['id']}.meta.json").write_text( json.dumps(meta, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" ) print(f"[{entry['id']}] wrote {len(records)} records -> {jsonl_path.name} " f"({meta['jsonl_bytes']} bytes, sha256 {meta['jsonl_sha256'][:16]}...)") return meta
def main(): parser = argparse.ArgumentParser(description="Build CORTEX datasets") parser.add_argument("--dataset", help="dataset id from registry.json") parser.add_argument("--all", action="store_true") parser.add_argument("--limit", type=int, default=200) args = parser.parse_args()
entries = load_registry()["datasets"] if args.all: selected = entries elif args.dataset: selected = [e for e in entries if e["id"] == args.dataset] if not selected: raise SystemExit(f"unknown dataset id: {args.dataset}") else: raise SystemExit("pass --dataset <id> or --all")
for entry in selected: build_dataset(entry, args.limit)
if __name__ == "__main__": main()123456789101112131415161718{ "id": "cortex-code-eval", "source": "openai/openai_humaneval", "config": "openai_humaneval", "split": "test", "origin": "Hugging Face Hub dataset repository openai/openai_humaneval", "license": "mit", "license_url": "https://huggingface.co/datasets/openai/openai_humaneval", "redistribution": "yes", "attribution": "HumanEval, OpenAI, distributed under the MIT license.", "record_type": "code-sft", "rows_fetched": 164, "records_written": 164, "jsonl_sha256": "3307ac92682622a9aa35a85cabe4bcb2bf79fe380b7aa0d8cc2720b947912c26", "jsonl_bytes": 121299, "note": "Held out for evaluation only. Must not be trained on: doing so would invalidate the evaluation.", "fetched_via": "https://datasets-server.huggingface.co/rows"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200{"text": "### Instruction\nCreate an array of length 5 which contains all even numbers between 1 and 10.\n\n### Response\narr = [2, 4, 6, 8, 10]", "source_id": ""}{"text": "### Instruction\nFormulate an equation to calculate the height of a triangle given the angle, side lengths and opposite side length.\n\n### Response\nHeight of triangle = opposite side length * sin (angle) / side length", "source_id": ""}{"text": "### Instruction\nWrite a replace method for a string class which replaces the given string with a given set of characters.\n\n### Response\ndef replace(self, replace_with):\n new_string = \"\"\n for char in self:\n if char == \" \":\n new_string += replace_with\n else:\n new_string += char\n return new_string", "source_id": ""}{"text": "### Instruction\nCreate an array of length 15 containing numbers divisible by 3 up to 45.\n\n### Response\narr = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45]", "source_id": ""}{"text": "### Instruction\nWrite a function to find the number of distinct states in a given matrix.\n\n### Response\ndef find_num_distinct_states(matrix):\n states = set()\n for row in matrix:\n state = \"\".join([str(x) for x in row])\n states.add(state)\n return len(states)", "source_id": ""}{"text": "### Instruction\nCreate a nested loop to print every combination of numbers between 0-9\n\n### Response\nfor i in range(10):\n for j in range(10):\n print(i, j)", "source_id": ""}{"text": "### Instruction\nWrite a function to find the maximum difference between two numbers in a given array.\n\n### Response\ndef max_difference(arr):\n max_diff = 0\n for i in range(len(arr)-1):\n diff = arr[i+1] - arr[i]\n if diff > max_diff:\n max_diff = diff\n return max_diff", "source_id": ""}{"text": "### Instruction\nWrite a function to generate the nth Fibonacci number.\n\n### Response\ndef fib(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fib(n-2) + fib(n-1)", "source_id": ""}{"text": "### Instruction\nWrite a class to represent a 2D point with x and y coordinates.\n\n### Response\nclass Point:\n def __init__(self, x, y):\n self.x = x \n self.y = y \n \n def __str__(self): \n return \"({0},{1})\".format(self.x, self.y)", "source_id": ""}{"text": "### Instruction\nWrite code that removes spaces from a given string.\n\n### Response\ndef remove_spaces(string): \n return \"\".join(string.split())", "source_id": ""}{"text": "### Instruction\nWrite a function that checks if a give number is even or odd.\n\n### Response\ndef is_even(n):\n if n%2 == 0:\n return True \n else:\n return False", "source_id": ""}{"text": "### Instruction\nWrite code to create a list of all prime numbers between 2 and 100.\n\n### Response\ndef find_primes(n): \n prime_list = [2] \n for number in range(2, n + 1): \n is_prime = True\n for k in range(2, number): \n if number % k == 0: \n is_prime = False \n if is_prime: \n prime_list.append(number) \n return prime_list", "source_id": ""}{"text": "### Instruction\nEdit the following code to print out all even numbers from 1 to 10.\n\n### Response\nfor i in range(1,11):\n if i % 2 == 0:\n print(i)", "source_id": ""}{"text": "### Instruction\nWrite code to find the sum of all numbers between 1 and 10.\n\n### Response\nsum = 0\nfor i in range(1,11):\n sum += i\nprint(sum)", "source_id": ""}{"text": "### Instruction\nCreate a function to calculate the area of a given circle.\n\n### Response\ndef area_circle(radius):\n return 3.14 * (radius**2)", "source_id": ""}{"text": "### Instruction\nFollow the comments in the code to complete the program which prints a conversion table from Fahrenheit to Celsius.\n\n### Response\n# This program prints a conversion table from Fahrenheit to Celsius\n\n# Print a heading for the table\nprint(\"Fahrenheit to Celsius Conversion Table\")\n\n# Print the column headings\nprint(\"Fahrenheit \\t Celsius\")\n\n# Calculate and print the table body\nfor fahr in range(-50 , 121):\n celsius = (fahr - 32) * 5 / 9\n print(\"%3d \\t\\t %.2f\" % (fahr, celsius))", "source_id": ""}{"text": "### Instruction\nDevelop a classification algorithm in Python to predict whether a bird is a hawk or a falcon.\n\n### Response\nimport pandas as pd\nimport numpy as np\n\n# Define features\nfeatures = [\"wing_shape\", \"size\", \"tails_length\", \"color_pattern\"] \n\n# Load the data\ndata = pd.read_csv(\"birds.csv\")\n\n# Preprocess the data to generate feature vectors\nX = np.array(data[features]) \n\n# Make a target vector \ny = np.array(data[\"species\"]) \n\n# Divide the data into training and test sets\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Train a classification model\nfrom sklearn.tree import DecisionTreeClassifier\nmodel = DecisionTreeClassifier()\nmodel.fit(X_train, y_train)\n\n# Make predictions\ny_pred = model.predict(X_test)\n\n# Generate evaluation metrics\nfrom sklearn.metrics import accuracy_score\naccuracy = accuracy_score(y_test, y_pred)\n\nprint(\"Model accuracy: %.2f\" % accuracy)", "source_id": ""}{"text": "### Instruction\nCreate a function in Java for computing the factorial of a positive integer number.\n\n### Response\npublic static long factorial(int n) {\n if (n == 0) {\n return 1;\n }\n long result = 1;\n for (int i = 1; i <= n; i++) {\n result *= i;\n }\n return result;\n}", "source_id": ""}{"text": "### Instruction\nCreate a C++ program for randomly shuffling an array of integers.\n\n### Response\n#include <iostream>\n#include <algorithm>\n#include <random>\n\nvoid shuffleArray(int array[], int size) {\n\tstd::random_device rd;\n\tstd::mt19937 g(rd()); \n\tstd::shuffle(array, array+size, g); \n}\n\nint main() \n{ \n\tint array[] = {1, 2, 3, 4, 5, 6, 7, 8}; \n\tint size = sizeof(array) / sizeof(array[0]); \n\n // Print original array\n std::cout << \"Original array: \";\n for (int i : array)\n std::cout << i << \" \";\n std::cout << \"\\n\";\n\n // Shuffle array\n\tshuffleArray(array, size); \n\n // Print shuffled array\n std::cout << \"Shuffled array: \";\n for (int i : array)\n std::cout << i << \" \";\n std::cout << \"\\n\";\n\n\treturn 0; \n}", "source_id": ""}{"text": "### Instruction\nUse the function to debug the given program and prevent the segmentation fault.\n\n### Response\n#include <stdio.h>\n\nint main() {\n int array[] = {1, 2, 3, 4, 5};\n int n = 5;\n int i;\n // Limit loop size to the length of the array\n for (i = 0; i < n; i++) {\n printf(\"%d\\n\", array[i]);\n }\n return 0;\n}", "source_id": ""}{"text": "### Instruction\nReplace the placeholder with a for loop for iterating over the numbers from 1 to n and printing them.\n\n### Response\nfor i in range(1, n+1):\n print(i)", "source_id": ""}{"text": "### Instruction\nUse try-except statements to detect and handle exceptions in the code.\n\n### Response\ntry:\n for i in range(n):\n x = 1/i\nexcept ZeroDivisionError:\n print(\"Zero division error encountered!\")", "source_id": ""}{"text": "### Instruction\nRe-write the code segment as a list comprehension.\n\n### Response\nnumbers = [i for i in range(10) if i % 2 == 0]", "source_id": ""}{"text": "### Instruction\nRemove the boilerplate code from the program for printing 10 random numbers.\n\n### Response\nimport random\n\n# Generate 10 random numbers\nfor i in range(10):\n print(random.randrange(1, 101))", "source_id": ""}{"text": "### Instruction\nModify the code to perform the mathematical expression “x to the power of y”.\n\n### Response\n# Calculate x to the power of y\nx_pow_y = x**y", "source_id": ""}{"text": "### Instruction\nCreate a dictionary for counting the occurrence of each letter in the given string.\n\n### Response\nstring = \"hello world\"\nletter_counts = {}\n\nfor letter in string:\n if letter in letter_counts:\n letter_counts[letter] += 1\n else:\n letter_counts[letter] = 1\n\nprint(letter_counts)", "source_id": ""}{"text": "### Instruction\nFollow the comments to complete the code that finds the maximum value in an array.\n\n### Response\n# Find the maximum value in an array\narr = [4, 5, 2, 8, 7]\n\nmax_value = arr[0]\nfor i in range(1, len(arr)):\n if arr[i] > max_value:\n max_value = arr[i]\n\nprint(max_value)", "source_id": ""}{"text": "### Instruction\nWrite a function in HTML for creating a table of n rows and m columns.\n\n### Response\n<table>\n <tbody>\n <% for (let i = 0; i < n; i++) { %>\n <tr>\n <% for (let j = 0; j < m; j++) { %>\n <td>Cell Content</td>\n <% } %>\n </tr>\n <% } %>\n </tbody>\n</table>", "source_id": ""}{"text": "### Instruction\nCreate a CSS script that centers the login form on the webpage.\n\n### Response\n.login-form {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n}", "source_id": ""}{"text": "### Instruction\nCreate a Java program that prints out the sum of the numbers in the array.\n\n### Response\npublic class SumOfArray {\n public static void main(String[] args) {\n int[] numbers = {1, 2, 3 , 4, 5};\n int sum = 0;\n for(int i=0; i < numbers.length;i++) {\n sum = sum + numbers[i];\n }\n System.out.println(\"The sum of numbers in the given array is: \" + sum);\n }\n}", "source_id": ""}{"text": "### Instruction\nWrite a SQL query to calculate the total number of orders in the \"orders\" table.\n\n### Response\nSELECT COUNT(*) AS \"Total Number of Orders\" \nFROM orders;", "source_id": ""}{"text": "### Instruction\nWrite a Python function to convert a given string to lowercase.\n\n### Response\ndef to_lowercase(string):\n return string.lower()\n\nstring = \"FOO\"\nprint(to_lowercase(string))", "source_id": ""}{"text": "### Instruction\nCreate a C program that prints out the Fibonacci sequence.\n\n### Response\n#include <stdio.h>\n\nint main()\n{\n int i, num, first=0, second=1, next;\n printf(\"Enter the number of elements: \");\n scanf(\"%d\", &num);\n printf(\"Fibonacci Series: \");\n for (i = 0; i < num; i++)\n {\n if (i <= 1)\n next = i;\n else\n {\n next = first + second;\n first = second;\n second = next;\n }\n printf(\"%d \", next);\n }\n return 0;\n}", "source_id": ""}{"text": "### Instruction\nWrite a function in JavaScript to count the number of vowels in a given string.\n\n### Response\nfunction countVowels(string) {\n let vowelCount = 0;\n const vowels = [\"a\",\"e\",\"i\",\"o\",\"u\"];\n \n for (let i = 0; i < string.length; i++) {\n if (vowels.includes(string[i])) {\n vowelCount++;\n }\n }\n \n return vowelCount;\n}\n\nconst string = \"abcdefg\";\nconsole.log(countVowels(string));", "source_id": ""}{"text": "### Instruction\nCreate a JSX code that renders a \"Hello, World!\" message in the browser.\n\n### Response\nimport React from \"react\";\n\nfunction App() {\n return (\n <div>\n <h1>Hello, World!</h1>\n </div>\n );\n}\n\nexport default App;", "source_id": ""}{"text": "### Instruction\nWrite an SQL query to calculate the average order price for each product category in the \"orders\" table.\n\n### Response\nSELECT category, AVG(price) as \"Average Order Price\"\nFROM orders\nGROUP BY category;", "source_id": ""}{"text": "### Instruction\nCreate a Java program that prints out the contents of a given two-dimensional array.\n\n### Response\npublic class TwoDArray {\n\n public static void main(String[] args) {\n int[][] arr = {{1,2},{3,4},{5,6}};\n\n for(int i=0;i<arr.length;i++){\n for(int j=0;j<arr[i].length;j++){\n System.out.print(arr[i][j]+\" \");\n }\n System.out.println();\n }\n }\n}", "source_id": ""}{"text": "### Instruction\nCreate a C++ program that sorts a given array in descending order.\n\n### Response\n#include<iostream>\nusing namespace std;\n \nint main()\n{\n int array[] = {6, 3, 8, 12, 9, 4};\n int arraySize = sizeof(array)/sizeof(array[0]);\n \n //ascending order sorting\n for(int i = 0; i < arraySize; i++)\n {\n // find the position of smallest element\n int small = i;\n for(int j = i+1; j < arraySize; j++)\n {\n if(array[j] > array[small])\n small = j;\n }\n \n // swap the position of smallest element\n int temp = array[i];\n array[i] = array[small];\n array[small] = temp;\n }\n \n // print the sorted array\n cout << \"Sorted array : \";\n for(int i = 0; i < arraySize; i++)\n cout << array[i] << \" \";\n \n return 0;\n}", "source_id": ""}{"text": "### Instruction\nEdit the Python code so that it prints out the total number of elements in the list.\n\n### Response\nlist = [1, 2, 3, 4, 5]\nprint(\"Total number of elements in the list: \", len(list))", "source_id": ""}{"text": "### Instruction\nCreate a Swift code that show the number of days in the given month.\n\n### Response\nlet month = 5\nlet daysEndingInth = [3, 0, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3]\nlet daysInMonth = daysEndingInth[month - 1] \nprint(\"The number of days in the month of \\(month) is \\(daysInMonth).\")", "source_id": ""}{"text": "### Instruction\nWrite a HTML code that create a form for user to fill out their current address.\n\n### Response\n<form action=\"\">\n <label for=\"street\">Street</label>\n <input type=\"text\" name=\"street\" id=\"street\">\n <label for=\"city\">City</label>\n <input type=\"text\" name=\"city\" id=\"city\">\n <label for=\"state\">State</label>\n <input type=\"text\" name=\"state\" id=\"state\">\n <label for=\"zip\">Zip Code</label>\n <input type=\"text\" name=\"zip\" id=\"zip\"> \n <input type=\"submit\" value=\"Submit\">\n</form>", "source_id": ""}{"text": "### Instruction\nWrite a SQL query to find the total number of orders placed between two given dates.\n\n### Response\nSELECT COUNT(*)\nFROM orders\nWHERE order_date BETWEEN '2020-01-01' AND '2020-02-01';", "source_id": ""}{"text": "### Instruction\nCreate a Ruby code that prints out the median of a given array of numbers.\n\n### Response\nnums = [1, 7, 3, 6]\nsorted_nums = nums.sort\n\n# Calculation of median \nif sorted_nums.length % 2 == 0\n mid_index = sorted_nums.length/2\n median = (sorted_nums[mid_index] + sorted_nums[mid_index - 1])/2.to_f\nelse\n mid_index = sorted_nums.length/2\n median = sorted_nums[mid_index]\nend\n\nputs median", "source_id": ""}{"text": "### Instruction\nCreate a PHP code to check if an array contains a given item.\n\n### Response\n<?php\n$input_array = array(1,2,3,4,5);\n$item_to_check = 3;\n\nif(in_array($item_to_check, $input_array)) {\n echo \"Array contains the given item.\";\n} else {\n echo \"Array doesn't contain the given item.\";\n}\n?>", "source_id": ""}{"text": "### Instruction\nEdit the code to create a try-except block to handle the exception.\n\n### Response\ntry:\n a = 5\n b = 0\n\n ans = a/b\nexcept ZeroDivisionError:\n print(\"Cannot divide by zero.\")", "source_id": ""}{"text": "### Instruction\nWrite a script using Bash that replaces all vowels with a number.\n\n### Response\n#!/bin/bash\n\nstring=\"Hello World!\"\nvowels=(\"a\" \"e\" \"i\" \"o\" \"u\" \"A\" \"E\" \"I\" \"O\" \"U\")\n\nfor i in \"${vowels[@]}\"\ndo\n string=\"${string//$i/0}\"\ndone\n\necho $string #H0ll0 W0rld!", "source_id": ""}{"text": "### Instruction\nChange the variable `x` to the data type desired.\n\n### Response\nx = \"Hello World!\"", "source_id": ""}{"text": "### Instruction\nCreate a function that takes an array as an argument and returns the sum of all the elements in the array.\n\n### Response\ndef arraySum(arr):\n total = 0\n for num in arr:\n total += num\n return total", "source_id": ""}{"text": "### Instruction\nSort the array in ascending order.\n\n### Response\narr.sort() # [1, 2, 3, 4, 5]", "source_id": ""}{"text": "### Instruction\nGenerate a random integer between 4 and 8 (inclusively).\n\n### Response\nimport random\nx = random.randint(4, 8)", "source_id": ""}{"text": "### Instruction\nWrite a list comprehension to square each number in the list.\n\n### Response\narr = [x**2 for x in arr] # [1, 4, 9, 16, 25]", "source_id": ""}{"text": "### Instruction\nWrite a function that takes a string and reverses the words.\n\n### Response\ndef reverseWords(text):\n return ' '.join(text.split()[::-1])\n\nreverseWords(text) # \"World! Hello\"", "source_id": ""}{"text": "### Instruction\nWrite a SQL query to return the sum of all salaries.\n\n### Response\nSELECT SUM(salary)\nFROM employees;", "source_id": ""}{"text": "### Instruction\nCreate a function that takes in two numbers as arguments and returns the product of the two.\n\n### Response\ndef multiply(x, y):\n return x*y", "source_id": ""}{"text": "### Instruction\nSum up the numbers in the array in Javascript.\n\n### Response\nlet sum = arr.reduce((total, num) => total + num);\nconsole.log(sum); // 15", "source_id": ""}{"text": "### Instruction\nUsing the given function, create a loop that counts from 0 to 9.\n\n### Response\nfor (let i = 0; i < 10; i++){\n printNum(i);\n}", "source_id": ""}{"text": "### Instruction\nCreate a JSON object with three key-value pairs.\n\n### Response\n{\n \"firstName\": \"John\",\n \"lastName\": \"Doe\",\n \"age\": 30\n}", "source_id": ""}{"text": "### Instruction\nCount the number of characters in the string.\n\n### Response\nlen(text) # 12", "source_id": ""}{"text": "### Instruction\nGenerate a random number between 0 and 1 (inclusively).\n\n### Response\nMath.random(); // a random number between 0 and 1 (inclusively)", "source_id": ""}{"text": "### Instruction\nCompose a function named average_list which takes a list of numbers as its argument and computes the average.\n\n### Response\ndef average_list(nums):\n return sum(nums)/len(nums)", "source_id": ""}{"text": "### Instruction\nGenerate a snippet of code to extract all the URLs from the given string.\n\n### Response\nimport re\n\nstring = \"This string contains some urls such as https://www.google.com and https://www.facebook.com.\"\n\nurls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string) \n\nprint(urls)", "source_id": ""}{"text": "### Instruction\nWrite a code to convert a given spredsheet in csv format to json format.\n\n### Response\nimport csv\nimport json\n\ndef csv_to_json():\n # Path of csv file\n file_csv = 'mycsvfile.csv'\n \n # Path of json file\n file_json = 'myjsonfile.json'\n \n with open(file_csv, 'r') as input_file:\n reader = csv.DictReader(input_file)\n data = list(reader)\n \n with open(file_json, 'w') as output_file:\n json.dump(data, output_file)\n\ncsv_to_json()", "source_id": ""}{"text": "### Instruction\nCreate a list comprehension to generate a list of multiples of 3 from 0 to 23.\n\n### Response\nlist_of_multiples_of_3 = [x*3 for x in range(8)]", "source_id": ""}{"text": "### Instruction\nDesign a program to find the longest element in the given list.\n\n### Response\ndef longest_element(list):\n max_length = 0\n max_length_item = None\n\n for item in list:\n if len(item) > max_length:\n max_length = len(item)\n max_length_item = item\n\n return max_length_item\n\nlist = [10, 100, 200, 500, 400]\nlongest_element(list) # 500", "source_id": ""}{"text": "### Instruction\nWrite a function to print all prime numbers between two given numbers.\n\n### Response\ndef print_prime_numbers_in_range(start, end):\n # start = starting number\n # end = ending number\n\n for num in range(start, end+1):\n # Prime numbers are greater than 1\n if num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n break\n else:\n print(num)\n---\n\n11. Instruction: Generate a snippet of code to reverse given string\n11. Input:\n<noinput>\n11. Output:\ndef reverse_string(input_string):\n string_length = len(input_string)\n reversed_string = \"\"\n \n for i in range(string_length-1,-1,-1):\n reversed_string += input_string[i]\n \n return reversed_string", "source_id": ""}{"text": "### Instruction\nDescribe the basic syntax of a Java function?\n\n### Response\nA Java function consists of a function name, return type, parameters (arguments), and body. The syntax of a Java function is as follows: \npublic <return type> <function name>(<list of parameters>) { \n // function body \n <statements> \n}", "source_id": ""}{"text": "### Instruction\nHow to reverse a list in C++?\n\n### Response\nYou can reverse a list in C++ using the std::reverse algorithm. To reverse the list, pass the list as the first parameter and the beginning and end of the list as the second and third parameter, respectively. Alternatively, you can also reverse the list using a for loop and the operator [] to access each element of the list.", "source_id": ""}{"text": "### Instruction\nWrite a SQL query to update a value x in a column y in a table z.\n\n### Response\nUPDATE payments \nSET amount = 5 \nWHERE payments.amount IS NOT NULL;", "source_id": ""}{"text": "### Instruction\nWrite an algorithm in Python to determine if a number is even or odd.\n\n### Response\ndef is_even(num): \n if num % 2 == 0: \n return True \n else: \n return False", "source_id": ""}{"text": "### Instruction\nWhat is the purpose of a constructor in a class in Java?\n\n### Response\nThe purpose of a constructor in a class in Java is to initialize an object of that class. A constructor is a special kind of method that is used to create an object of its associated class. When an object of the class is created, the constructor is used to set the initial state of the object.", "source_id": ""}{"text": "### Instruction\nWrite a JavaScript code to get the current browser URL.\n\n### Response\nvar currentURL = window.location.href;\nconsole.log(currentURL);", "source_id": ""}{"text": "### Instruction\nRewrite the following C++ code using only pointer references instead of array subscripts:\n\n### Response\nint arr[3] = {1,2,3};\nint sum = 0;\nint* ptr = arr;\nfor (int i = 0; i < 3; i++) \n{\n sum += *(ptr+i); \n}", "source_id": ""}{"text": "### Instruction\nWrite a MySQL query to print the column names of a table named 'employees'.\n\n### Response\nSELECT column_name FROM information_schema.columns WHERE table_name = 'employees';", "source_id": ""}{"text": "### Instruction\nGenerate a regular expression to match a valid email address.\n\n### Response\n/^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$/", "source_id": ""}{"text": "### Instruction\nHow to delete a particular row in an SQLite database table?\n\n### Response\nTo delete a particular row in an SQLite database table, you can use the DELETE statement with a WHERE clause to specify the row to be deleted. For example: DELETE FROM table_name WHERE condition;", "source_id": ""}{"text": "### Instruction\nIs it possible to set a breakpoint that is not associated with any source code line in a GDB program?\n\n### Response\nYes, it is possible to set a breakpoint that is not associated with any source code line in a GDB program. For example, you can set a breakpoint on a function or a memory address. You can do this by using the break command with '*' prefix followed by the address of the breakpoint.", "source_id": ""}{"text": "### Instruction\nWrite a C++ code to find the average of an array of integers.\n\n### Response\n#include <iostream>\n\nint calculateAverage(int array[], int n){\n int sum = 0; \n for (int i=0; i<n; i++){\n sum += array[i]; \n } \n int average = sum/n;\n return average;\n}", "source_id": ""}{"text": "### Instruction\nHow can we encrypt a string in Python?\n\n### Response\nWe can encrypt a string in Python using the cryptography module. The cryptography module provides high level cryptographic primitives using the Fernet cipher. The Fernet cipher uses AES-128 in CBC mode and PKCS7 padding to encrypt the string.", "source_id": ""}{"text": "### Instruction\nWhat is the purpose of declaring a function as static in C++?\n\n### Response\nThe purpose of declaring a function as static in C++ is to restrict its visibility to only the translation unit in which it is declared. A static function can only be called from within the same translation unit and thus, it cannot be accessed from outside of that translation unit.", "source_id": ""}{"text": "### Instruction\nHow to print the elements of a two-dimensional array in C?\n\n### Response\nWe can use nested loops to print the elements of a two-dimensional array in C. The outer loop iterates over the rows, while the inner loop iterates over the columns. For example, the following code snippet prints the elements of a two-dimensional array: \n \nint array[3][3] = {{1,2,3},{4,5,6},{7,8,9}};\nfor (int i=0; i<3; i++)\n{ \n for(int j=0; j<3; j++) \n {\n printf(\"%d \", array[i][j]); \n }\n printf(\"\\n\");\n}", "source_id": ""}{"text": "### Instruction\nUsing the following code, clean up the bugs and make sure the output functions correctly.\n\n### Response\ndef example_func(lst):\n output_lst = []\n for element in lst:\n if (type(element) == int):\n output_lst.append(element + 5)\n return output_lst\n \nexample_func([1, 2, \"hello\"])", "source_id": ""}{"text": "### Instruction\nWrite a C++ function to generate a random integer between 0 and 10.\n\n### Response\n#include <iostream> \n#include <cstdlib> \n#include <ctime> \nusing namespace std; \n\nint randomIntGenerator() \n{ \n // Setting the seed \n srand(time(0)); \n\n // Generating random integer \n return (rand()%11); \n}", "source_id": ""}{"text": "### Instruction\nCreate a table to store customer information.\n\n### Response\nCREATE TABLE customers (\n id int NOT NULL AUTO_INCREMENT,\n name varchar(100) NOT NULL,\n email varchar(100) NOT NULL,\n phone varchar(20) NOT NULL,\n address varchar(200) NOT NULL,\n PRIMARY KEY (id)\n);", "source_id": ""}{"text": "### Instruction\nCreate a class in Java named Puppy that has two instance variables, age and name and two methods, bark and sleep.\n\n### Response\npublic class Puppy { \n // Instance Variables \n String name; \n int age; \n \n // Constructor \n public Puppy(String name, int age){ \n this.name = name; \n this.age = age; \n } \n \n // Methods \n public void bark(){ \n System.out.println(\"Woof Woof!\"); \n } \n \n public void sleep(){ \n System.out.println(\"Zzzzzz...\"); \n } \n}", "source_id": ""}{"text": "### Instruction\nParse the string and return the number of unique alphabets in the string.\n\n### Response\nint count = 0;\nfor (int i = 0; i < StringInput.length(); i++) {\n if ((StringInput.charAt(i) >= 'a' && StringInput.charAt(i) <= 'z') || (StringInput.charAt(i) >= 'A' && StringInput.charAt(i) <= 'Z')) {\n count++;\n }\n}\nSystem.out.println(\"Number of unique alphabets: \" + count);", "source_id": ""}{"text": "### Instruction\nWrite a shell script to print the top 3 most frequently used commands.\n\n### Response\n#!/bin/bash\n# Store all commands used in the last hour in command_list.\nhistory | tail -$(($(date +%H) * 60)) -n $(($(date +%M)+1)) | cut -d ' ' -f 5 > command_list\n# Create frequency database and store them in frequency.dat\ncat command_list | sort | uniq -c | sort -rn > frequency.dat\n# Print top 3 commands\nhead -3 frequency.dat", "source_id": ""}{"text": "### Instruction\nRead the JSON string below and convert it into a dictionary.\n\n### Response\nimport json\n\njsonObject = json.loads(jsonString)\ndictionary = dict(jsonObject)\nprint(dictionary)", "source_id": ""}{"text": "### Instruction\nImplement a function that finds the maximum element in a given array.\n\n### Response\ndef find_max_element(arr): \n max_element = arr[0] \n for index in range(1, len(arr)): \n if arr[index] > max_element: \n max_element = arr[index] \n return max_element\n \narr = [45, 7, 0, 82, 23]\nmax_element = find_max_element(arr) \nprint(max_element)", "source_id": ""}{"text": "### Instruction\nValidate whether the string contains only alphabets or not.\n\n### Response\ndef check_string_alphabets(myString):\n for character in myString:\n if (not character.isalpha()):\n return False\n return True\n\nmyString = \"abc123\"\nif (check_string_alphabets(myString)):\n print(\"String contains only alphabets\")\nelse:\n print(\"String contains numbers\")", "source_id": ""}{"text": "### Instruction\nRewrite the following code using ternary operator.\n\n### Response\nnum1 = 5\nnum2 = 10\n\nprint(\"num1 is smaller than num2\") if (num1 < num2) else print(\"num1 is greater than or equal to num2\")", "source_id": ""}{"text": "### Instruction\nWrite a script to check if a given number is a palindrome or not.\n\n### Response\n# Function to check whether the inputNumber is palindrome or not\ndef is_palindrome(inputNumber):\n\n # negative numbers are not palindrome\n if inputNumber < 0:\n return False\n\n # find the number of digits in the inputNumber\n div = 1\n while (inputNumber / div >= 10):\n div *= 10\n\n # check if the most significant and least significant digits match\n while (inputNumber != 0):\n # compare first and last digits\n firstdigit = inputNumber // div\n lastdigit = inputNumber % 10\n if firstdigit != lastdigit:\n return False\n\n # remove the most and least significant digit of inputNumber\n inputNumber = (inputNumber % div) // 10\n\n # reduce div by a factor of 2, since 2 digits\n # were removed\n div = div // 100\n return True\n\n# Driver code to test above\ninputNumber = 121\nif is_palindrome(inputNumber) :\n print(\"Yes\")\nelse:\n print(\"No\")", "source_id": ""}{"text": "### Instruction\nEdit the following code to remove the bugs.\n\n### Response\ndef reverse_string(user_string): \n reversed_string = ''\n if len(user_string) == 0: \n return \"\" \n else: \n reversed_string = reverse_string(user_string[1:]) + user_string[0] \n return reversed_string\n\nuser_string = 'test'\nprint(reverse_string(user_string))", "source_id": ""}{"text": "### Instruction\nWhat is the output of the following code?\n\n### Response\na\nbb\nccc", "source_id": ""}{"text": "### Instruction\nWrite a function to remove all whitespace characters from a given string.\n\n### Response\ndef remove_whitespaces(myString):\n return ''.join(myString.split())\n\nmyString = \"Hello World \"\nprint(remove_whitespaces(myString))", "source_id": ""}{"text": "### Instruction\nEdit the following code to add try catch block.\n\n### Response\nx = \"5\"\ny = \"2\"\ntry:\n sum = int(x) + int(y)\n print(\"Sum of x and y is\", sum)\nexcept:\n print(\"Error: Invalid input\")", "source_id": ""}{"text": "### Instruction\nWrite a Python function that takes two lists of equal length and creates a dictionary of the elements in each list that have the same index.\n\n### Response\ndef list_dict(list_one, list_two):\n \"\"\"Create a dictionary of elements in the two lists which have the same index.\"\"\"\n assert len(list_one) == len(list_two), \"lists must be same length\"\n dict = {}\n for i in range(len(list_one)):\n dict[list_one[i]] = list_two[i]\n return dict", "source_id": ""}{"text": "### Instruction\nCreate a quick-sort algorithm in Python.\n\n### Response\ndef quick_sort(arr):\n \"\"\"Sort a list of numbers in ascending order using the Quick-Sort algorithm\"\"\"\n if len(arr) == 0:\n return []\n\n pivot = arr[0]\n left_arr = [x for x in arr if x < pivot]\n right_arr = [x for x in arr if x > pivot]\n return quick_sort(left_arr) + [pivot] + quick_sort(right_arr)", "source_id": ""}{"text": "### Instruction\nDevelop an algorithm to find the value of n where n is the index of the Fibonacci sequence.\n\n### Response\ndef nth_fibonacci_number(n):\n \"\"\"Find the value of n where n is the index of the Fibonacci Sequence.\"\"\" \n if n < 2:\n return n \n elif n == 2:\n return 1\n else:\n return nth_fibonacci_number(n-1) + nth_fibonacci_number(n-2)", "source_id": ""}{"text": "### Instruction\nCreate a program that finds all the prime numbers less than or equal to a given number.\n\n### Response\ndef find_primes(num):\n \"\"\"Find all the prime numbers less than or equal to a given number.\"\"\"\n primes = []\n for i in range(2, num + 1):\n is_prime = True\n for j in range(2, int(i ** 0.5) + 1):\n if i % j == 0:\n is_prime = False\n break\n if is_prime:\n primes.append(i)\n return primes", "source_id": ""}{"text": "### Instruction\nWrite a function that takes in a list of numbers and prints out the greatest number.\n\n### Response\ndef find_greatest(list):\n \"\"\"Print out the greatest number from a list of numbers.\"\"\"\n greatest = list[0]\n for num in list:\n if num > greatest:\n greatest = num\n print('The greatest number is: ', greatest)", "source_id": ""}{"text": "### Instruction\nDesign an algorithm that takes a list of strings and returns the longest string.\n\n### Response\ndef find_longest(list):\n \"\"\"Return the longest string from a list of strings.\"\"\" \n longest = list[0]\n for item in list:\n if len(item) > len(longest):\n longest = item\n return longest", "source_id": ""}{"text": "### Instruction\nWrite a function that takes in a matrix of numbers and reverses the order of the rows and columns.\n\n### Response\ndef reverse_matrix(matrix):\n \"\"\"Reverse the order of the rows and columns in a matrix of numbers.\"\"\"\n reversed_matrix = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n reversed_matrix[j][i] = matrix[i][j]\n return reversed_matrix", "source_id": ""}{"text": "### Instruction\nDesign an algorithm that creates a random password of 8 characters.\n\n### Response\ndef generate_password():\n \"\"\"Generate a random password of 8 characters.\"\"\"\n import random\n chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()'\n password = ''\n for i in range(8):\n password += random.SystemRandom().choice(chars)\n return password", "source_id": ""}{"text": "### Instruction\nFOr a given list, create a program that prints out the standard deviation of the elements in the list.\n\n### Response\ndef std_dev(list):\n \"\"\"Print the standard deviation of elements in a given list.\"\"\"\n numerator = 0\n mean = sum(list) / len(list)\n for num in list:\n numerator += (num - mean) ** 2\n sd = (numerator / (len(list) - 1)) ** 0.5\n return sd", "source_id": ""}{"text": "### Instruction\nCreate a program that can filter out words of a string that contain a specific character.\n\n### Response\ndef filter_string(string, character):\n \"\"\"Filter out words of a string that contain a specific character.\"\"\"\n words = string.split(' ')\n filtered_words = []\n for word in words:\n if character not in word:\n filtered_words.append(word)\n return ' '.join(filtered_words)", "source_id": ""}{"text": "### Instruction\nCreate a program that can calculate the distance between two points in three-dimensional space.\n\n### Response\ndef dist_points_3d(point1, point2):\n \"\"\"Calculate the distance between two points in three-dimensional space.\"\"\"\n distance = ((point1[0] - point2[0]) ** 2 + \n (point1[1] - point2[1]) ** 2 + \n (point1[2] - point2[2]) ** 2) ** 0.5\n return distance", "source_id": ""}{"text": "### Instruction\nCreate a program that ciphers a given text using the caesar cipher.\n\n### Response\ndef caesar_cipher(text, key):\n \"\"\"Cipher a given text using the Caesar Cipher.\"\"\"\n ciphertext = \"\"\n for char in text: \n if not char.isalpha():\n ciphertext += char\n continue\n offset = ord('a') if char.islower() else ord('A')\n new_char = (ord(char) - offset + key) % 26\n ciphertext += chr(offset + new_char)\n return ciphertext", "source_id": ""}{"text": "### Instruction\nFind the second smallest element in an integer array of size n.\n\n### Response\ndef second_smallest(array):\n\nsmallest = min(array)\nsecond_smallest = float('inf')\n\nfor num in array:\n if num > smallest and num < second_smallest:\n second_smallest = num\n \nreturn second_smallest", "source_id": ""}{"text": "### Instruction\nWrite a SQL query to find all the users in a database with age greater than 25.\n\n### Response\nSELECT * FROM users WHERE age > 25", "source_id": ""}{"text": "### Instruction\nCreate a function to calculate the maximum of two numbers.\n\n### Response\ndef max_of_two(x, y):\n if x > y:\n return x\n else:\n return y", "source_id": ""}{"text": "### Instruction\nWrite a Python program to split a string on a given character separator.\n\n### Response\ndef split(mystring, separator):\n return mystring.split(separator)", "source_id": ""}{"text": "### Instruction\nWrite a Python program to get the day of week from a given date and time.\n\n### Response\nfrom datetime import datetime\n\ndef get_day_of_week(date):\n return date.strftime(\"%A\")", "source_id": ""}{"text": "### Instruction\nWrite a Javascript function to determine if the given number is an even number or not.\n\n### Response\nfunction isEven(num) {\nreturn num % 2 === 0;\n}", "source_id": ""}{"text": "### Instruction\nWrite a Python program to print out an ASCII art of a given word.\n\n### Response\ndef draw_word(word):\n art = \"\"\"\n __\n _ / \\\\\n \\\\_/\\_/\\_/\n / |\n \\___/\n \\\\\\\\_//\n \\/ \\/\n \\/\n \"\"\"\n for letter in word:\n art += \" \" + letter\n print(art)", "source_id": ""}{"text": "### Instruction\nWrite a JavaScript function to validate a given URL.\n\n### Response\nfunction isValidURL(url) {\n const regex = /^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&'\\(\\)\\*\\+,;=.]+$/;\n return regex.test(url);\n}", "source_id": ""}{"text": "### Instruction\nWrite a C# program to find the maximum and minimum of three numbers.\n\n### Response\npublic void Maximum_Minimum(int num1, int num2, int num3)\n{\n int max = Math.Max(Math.Max(num1, num2),num3);\n int min = Math.Min(Math.Min(num1,num2),num3);\n Console.WriteLine(\"Maximum Number is : \" + max);\n Console.WriteLine(\"Minimum Number is : \" + min);\n}", "source_id": ""}{"text": "### Instruction\nWrite a Java program to reverse a given string.\n\n### Response\npublic class ReverseString\n{ \n\n public static void main(String[] args) \n { \n String input = \"Hello\"; \n StringBuilder input1 = new StringBuilder(); \n \n // append a string into StringBuilder input1 \n input1.append(input); \n \n // reverse StringBuilder input1 \n input1 = input1.reverse(); \n \n // print reversed String \n System.out.println(input1); \n } \n}", "source_id": ""}{"text": "### Instruction\nWrite an HTML template to display a greeting message. The message should include the name of the user who visits the website.\n\n### Response\n<html>\n\t<head>\n\t\t<title>Greeting Message</title>\n\t</head>\n\t<body>\n\t\t<h1>Hello, {{ username }}!</h1>\n\t</body>\n</html>", "source_id": ""}{"text": "### Instruction\nWrite a Python program to concatenate all elements in a list into a string separated by a given separator.\n\n### Response\ndef list_to_string(input_list, separator):\n return separator.join(input_list)", "source_id": ""}{"text": "### Instruction\nWrite a C program to find the sum of all digits of a given number\n\n### Response\n#include <stdio.h>\n\nint getSumOfDigits(int num) {\n // Initialize sum\n int sum = 0;\n\n // Find the sum of digits\n while(num > 0) {\n sum += num % 10;\n num /= 10;\n }\n\n return sum;\n}\n\nint main() {\n int num;\n scanf(\"%d\", &num);\n\n printf(\"Sum of digits of %d is %d\\n\", num, getSumOfDigits(num));\n\n return 0;\n}", "source_id": ""}{"text": "### Instruction\nWrite a Java program to generate random numbers\n\n### Response\nimport java.util.Random; \n \npublic class GenerateRandom { \n \n public static void main(String[] args) \n { \n \n Random rand = new Random(); \n \n // Generate random integers in range 0 to 999 \n int x = rand.nextInt(1000); \n System.out.println(\"Random Integers: \" + x); \n \n // Generate Random doubles \n double y = rand.nextDouble(); \n System.out.println(\"Random Doubles: \" + y); \n \n // Generate Random Boolean \n boolean z = rand.nextBoolean(); \n System.out.println(\"Random Boolean: \" + z); \n } \n}", "source_id": ""}{"text": "### Instruction\nRewrite the following Python code using a for-loop.\n\n### Response\nfor i in range(11):\n print(i)", "source_id": ""}{"text": "### Instruction\nWrite a code to print the current date and time in ISO format.\n\n### Response\nfrom datetime import datetime\n\ndate_time_obj = datetime.now()\n\nprint(date_time_obj.isoformat()) # prints \"2020-07-29T15:10:01.584131\"", "source_id": ""}{"text": "### Instruction\nCreate a new folder called 'data' within the current working directory.\n\n### Response\nimport os\n\n# create 'data' folder in the current working directory\ncurrent_directory = os.getcwd()\nnew_directory = os.path.join(current_directory, 'data')\nos.mkdir(new_directory)", "source_id": ""}{"text": "### Instruction\nWrite a code to sort the following array in increasing order.\n\n### Response\n# sorting array using insertion sort\narr = [10, 2, 7, 8, 32, 4] \n\n# traverse through all array elements \nfor i in range(1, len(arr)):\n key = arr[i]\n\n # move elements of arr[0..i-1], that are greater than key,\n # to one position ahead of their current position\n j = i-1\n while j >= 0 and key < arr[j] : \n arr[j + 1] = arr[j] \n j -= 1\n arr[j + 1] = key\n \n#print the sorted array\nprint(arr)", "source_id": ""}{"text": "### Instruction\nCreate a function in JavaScript that takes an array of integers and returns the largest number.\n\n### Response\nfunction findMax(arr) {\n let max = arr[0];\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] > max) {\n max = arr[i];\n }\n }\n return max;\n}", "source_id": ""}{"text": "### Instruction\nCreate a regular expression to validate a URL string.\n\n### Response\n# Regular expression to validate a URL string\n^(http:\\/\\/|https:\\/\\/|ftp:\\/\\/)?(www\\.)?([a-zA-Z0-9]+(-?[a-zA-Z0-9])*\\.)+[\\w]{2,5}(\\/\\S*)?$", "source_id": ""}{"text": "### Instruction\nWrite a Python code to calculate the mean of a given array.\n\n### Response\n# calculate the mean of given array\narr = [1,2,3,4]\n\ndef calc_mean(arr):\n sum = 0\n for num in arr:\n sum += num\n return sum / len(arr)\n\nprint(calc_mean(arr)) # prints 2.5", "source_id": ""}{"text": "### Instruction\nCreate a function in Java that takes a string and prints the reversed version.\n\n### Response\npublic static void reverseString(String str) { \n StringBuilder sb = new StringBuilder(); \n \n for (int i = str.length() - 1; i >= 0; i--) { \n sb.append(str.charAt(i)); \n } \n \n System.out.print(sb.toString()); \n}", "source_id": ""}{"text": "### Instruction\nWrite a code to get the time difference between two date-time objects.\n\n### Response\nfrom datetime import datetime\n\ndef time_difference(date1, date2):\n date1_obj = datetime.strptime(date1, '%Y-%m-%d %H:%M:%S')\n date2_obj = datetime.strptime(date2, '%Y-%m-%d %H:%M:%S')\n\n return (date2_obj - date1_obj).total_seconds() // 3600\n\nprint(time_difference('2019-05-11 21:00:00', '2019-05-13 10:00:00')) # prints 33.0", "source_id": ""}{"text": "### Instruction\nWrite a code to connect to a remote database.\n\n### Response\nimport psycopg2\n\nconn = psycopg2.connect(host=\"100.10.0.10\", database=\"mydb\", user=\"john\", password=\"john123\")", "source_id": ""}{"text": "### Instruction\nCreate an HTML form with a textbox, a submit button, and two radio buttons.\n\n### Response\n<form>\n <input type=\"text\" id=\"textbox\">\n <input type=\"submit\" value=\"Submit\">\n <input type=\"radio\" name=\"choice\" value=\"yes\">Yes\n <input type=\"radio\" name=\"choice\" value=\"no\">No\n</form>", "source_id": ""}{"text": "### Instruction\nWrite a code to access the nth element of a linked list.\n\n### Response\n# defining the Node class\nclass Node: \n\tdef __init__(self, data): \n\t\tself.data = data \n\t\tself.next = None\n\ndef getNthElement(head, n): \n\tcurrent = head \n\tcount = 0\n\n\t# looping through the linked list\n\twhile(current is not None): \n\t\tif (count == n): \n\t\t\treturn current.data \n\t\tcount += 1\n\t\tcurrent = current.next\n\treturn -1", "source_id": ""}{"text": "### Instruction\nCreate a function in JavaScript to find the number of occurrences of a letter in a word.\n\n### Response\nfunction findOccurrences(word, letter) {\n let count = 0;\n for (let i = 0; i < word.length; i++) {\n if (word.charAt(i) === letter) {\n count++;\n }\n }\n return count;\n}", "source_id": ""}{"text": "### Instruction\nWrite a code to add two linked lists of different sizes.\n\n### Response\n# adding two linked lists\nclass Node: \n\tdef __init__(self, data): \n\t\tself.data = data \n\t\tself.next = None\n\ndef addTwoLists(first, second):\n # defining current and prev variables\n prev = None\n carry = 0\n temp = None\n\n # looping until one list has all nodes added\n while(first is not None or second is not None): \n Node = Node() \t\t# Node data\n\n Node.data = carry + (first.data if first else 0) + (second.data if second else 0) \n\t\t\n # update carry\n if Node.data >= 10: \n Node.data = Node.data % 10\n carry = 1\n else: \n carry = 0\n \n temp = Node\n # Move first, second pointers ahead\n if first is not None: \n first = first.next\n if second is not None: \n second = second.next\n\n # Attach the previous node to the current node\n if prev is not None: \n prev.next = Node \n prev = Node\n\t\t\n if carry > 0: \n temp.next = Node \n temp.data = carry \n return result", "source_id": ""}{"text": "### Instruction\nCreate a function in Java to convert a list of strings to a 2D array.\n\n### Response\npublic static String[][] convertTo2DArray(List<String> strings) {\n int n = strings.size();\n String[][] array = new String[n][1];\n for (int i = 0; i < n; i++) {\n array[i][0] = strings.get(i);\n }\n return array;\n \n}", "source_id": ""}{"text": "### Instruction\nModify the code below to make it calculate the sum of all the numbers from 1 to n.\n\n### Response\nnum = 5\nsum = 0\nfor i in range(1, num+1):\n sum += i", "source_id": ""}{"text": "### Instruction\nCreate a program to generate a histogram using data from a set of numbers.\n\n### Response\nimport matplotlib.pyplot as plt\n\nvalues = [3, 4, 2, 5, 8, 1, 2, 6]\n\nplt.hist(values, bins= 10, edgecolor='black', color='b')\n\nplt.xlabel('Values')\nplt.ylabel('Frequency')\n\nplt.title('Histogram')\n\nplt.show()", "source_id": ""}{"text": "### Instruction\nCreate a function to convert Celsius to Fahrenheit.\n\n### Response\ndef celsius_to_fahrenheit(c):\n f = c * (9/5) + 32\n return f", "source_id": ""}{"text": "### Instruction\nWrite a function to find the number of occurrences of an element in a list.\n\n### Response\ndef count_occurrences(arr, element):\n count = 0\n for e in arr:\n if e == element:\n count += 1\n return count\n\nprint(count_occurrences(arr, 40)) # Outputs: 3", "source_id": ""}{"text": "### Instruction\nWrite a JavaScript code snippet to print the numbers from 1 to 10.\n\n### Response\nfor (let i = 1; i <= 10; i++) {\n console.log(i);\n}", "source_id": ""}{"text": "### Instruction\nGenerate a dictionary of 10 key-value pairs, where the key is a string and the values are random numbers from 1 to 100.\n\n### Response\nimport random\n\nd = dict()\n\nkeys = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"]\n\nfor key in keys:\n d[key] = random.randint(1,100)\n\nprint(d)", "source_id": ""}{"text": "### Instruction\nCreate a JavaScript function which takes a string as a parameter and returns the most frequent character in the string.\n\n### Response\nfunction mostFrequentChar(string) {\n let charMap = {};\n let maxCount = 0;\n let freqChar = '';\n \n for (let char of string) {\n if (charMap[char]) {\n charMap[char]++;\n } else {\n charMap[char] = 1;\n }\n }\n \n for (let char in charMap) {\n if (charMap[char] > maxCount) {\n maxCount = charMap[char];\n freqChar = char;\n }\n }\n \n return freqChar;\n}", "source_id": ""}{"text": "### Instruction\nWrite a C# function which takes 2 strings as parameters and returns a new string which is a concatenation of the two parameters.\n\n### Response\nstring ConcatenateStrings(string str1, string str2)\n{\n return str1 + str2;\n}", "source_id": ""}{"text": "### Instruction\nCreate an HTML page where the main content area has a random background color when the page is loaded.\n\n### Response\n<!DOCTYPE html>\n<html>\n <head>\n <title>RandomBackground</title>\n <script>\n window.addEventListener(\"load\",function(){\n var randomColor = \"#\"+((1<<24)*Math.random()|0).toString(16);\n document.querySelector(\"body\").style.background = randomColor;\n });\n </script>\n </head>\n <body>\n </body>\n</html>", "source_id": ""}{"text": "### Instruction\nCreate a Java program which takes an integer array as a parameter, sorts the array in ascending order, and returns the sorted array.\n\n### Response\npublic int[] SortIntegerArray(int[] nums)\n{\n Arrays.sort(nums);\n return nums;\n}", "source_id": ""}{"text": "### Instruction\nWrite an SQL query to select the number of employees in each department, sorted by the department name in ascending order.\n\n### Response\nSELECT department, COUNT(employee_ID)\nFROM employees\nGROUP BY department\nORDER BY department ASC;", "source_id": ""}{"text": "### Instruction\nWrite a Python program to remove all instances of a given value from a given list.\n\n### Response\ndef remove_value(nums, val):\n res = []\n for num in nums:\n if num != val:\n res.append(num)\n return res", "source_id": ""}{"text": "### Instruction\nCreate a Java program to take a given string and replace all occurrences of a given letter with another given letter\n\n### Response\npublic String ReplaceLetters(String str, char oldChar, char newChar) {\n return str.replace(oldChar, newChar);\n}", "source_id": ""}{"text": "### Instruction\nWrite an SQL query to calculate the average salary of all employees in a table, rounded to the nearest integer.\n\n### Response\nSELECT ROUND(AVG(salary))\nFROM employees;", "source_id": ""}{"text": "### Instruction\nCreate a JavaScript function that takes a given sentence as a parameter and capitalizes the first letter of each word.\n\n### Response\nfunction capitalizeSentence(str) {\n let words = str.split(' ');\n let res = [];\n \n for (let word of words) {\n res.push(word[0].toUpperCase() + word.slice(1));\n }\n \n return res.join(' ');\n}", "source_id": ""}{"text": "### Instruction\nWrite a Python program to generate the first n Fibonacci numbers.\n\n### Response\ndef generate_fibonacci_numbers(n):\n if n==1:\n return [0]\n elif n==2:\n return [0,1]\n else:\n fib_list = [0,1]\n for i in range(2,n):\n fib_list.append(fib_list[i-1]+fib_list[i-2])\n return fib_list", "source_id": ""}{"text": "### Instruction\nCreate a C# program which takes two strings as parameters, and returns true if the two strings are anagrams of each other.\n\n### Response\nbool AreAnagrams(string s1, string s2)\n{\n if (s1.Length != s2.Length)\n return false;\n \n int[] a = new int[256];\n int n = s1.Length;\n for (int i = 0; i < n; i++)\n {\n int c1 = (int)s1[i];\n int c2 = (int)s2[i];\n \n a[c1]++;\n a[c2]--;\n }\n \n for (int i = 0; i < 256; i++)\n {\n if (a[i] != 0)\n return false;\n }\n \n return true;\n}", "source_id": ""}{"text": "### Instruction\nWrite an SQL query to calculate the difference between the total salaries of male and female employees in a table.\n\n### Response\nSELECT SUM(CASE WHEN gender = 'female' THEN salary ELSE 0 END) - SUM(CASE WHEN gender = 'male' THEN salary ELSE 0 END)\nFROM employees;", "source_id": ""}{"text": "### Instruction\nCreate a JavaScript program which takes an array of integers as a parameter and reverses the array in-place.\n\n### Response\nfunction reverseArrayInPlace(nums) {\n let left = 0;\n let right = nums.length - 1;\n \n while (left < right) {\n let temp = nums[left];\n nums[left] = nums[right];\n nums[right] = temp;\n \n left++;\n right--;\n }\n return nums;\n}", "source_id": ""}{"text": "### Instruction\nExplain what the following line of code does.\n\n### Response\nThis line of code assigns the remainder of a divided by b to a, so that the resulting value of a is the remainder of a divided by b. For example, if a is 10 and b is 3, the value of a after executing this line of code would be 1 (the remainder of 10 divided by 3).", "source_id": ""}{"text": "### Instruction\nConstruct an if-else statement that returns ‘even’ if the given number is even and ‘odd’ if the given number is odd.\n\n### Response\nif n % 2 == 0:\n return 'even'\nelse:\n return 'odd'", "source_id": ""}{"text": "### Instruction\nMultiply two vectors of size 5 and return the output.\n\n### Response\n[5, 8, 9, 8, 5]", "source_id": ""}{"text": "### Instruction\nCreate a list comprehension that takes all the elements of list_one and creates a new list where all the elements are doubled.\n\n### Response\n[x*2 for x in list_one]", "source_id": ""}{"text": "### Instruction\nYou are given a matrix of m rows and n columns. Write a function that calculates the transpose of the given matrix.\n\n### Response\ndef transpose(matrix):\n m = len(matrix)\n n = len(matrix[0])\n\n transpose_matrix = [[0] * m for _ in range(n)]\n for i in range(m):\n for j in range(n):\n transpose_matrix[j][i] = matrix[i][j]\n\n return transpose_matrix", "source_id": ""}{"text": "### Instruction\nGiven a list of numbers, print the difference between the largest and the smallest number.\n\n### Response\ndifference = max(list_of_numbers) - min(list_of_numbers)\nprint(difference)", "source_id": ""}{"text": "### Instruction\nCreate a for loop that goes through every element of list_of_words and prints ‘success’ if an element is equal to “example” and prints ‘failure’ in any other case.\n\n### Response\nfor word in list_of_words:\n if word == \"example\":\n print(\"success\")\n else:\n print(\"failure\")", "source_id": ""}{"text": "### Instruction\nCreate a function that takes in a list of temperatures and returns the average temperature\n\n### Response\ndef average_temperature(temperatures):\n num_items = len(temperatures)\n sum_items = 0\n for temperature in temperatures:\n sum_items += temperature\n return sum_items / num_items", "source_id": ""}{"text": "### Instruction\nYou are given a list of numbers. Create a function that returns a new list with duplicates removed\n\n### Response\ndef remove_duplicates(numbers):\n new_list = []\n for num in numbers:\n if num not in new_list:\n new_list.append(num)\n return new_list", "source_id": ""}{"text": "### Instruction\nIn a given string, create a function that returns the longest consecutive sequence of characters.\n\n### Response\ndef longest_consecutive(string):\n character_list = []\n max_length = 0\n max_sequence = ''\n for char in string:\n if char in character_list:\n continue\n else:\n character_list.append(char)\n current_length = 1\n for i in range(1, len(string)):\n if string[i-1] == char and string[i] == char:\n current_length += 1\n if current_length>max_length:\n max_length = current_length\n max_sequence = char*max_length\n return max_sequence", "source_id": ""}{"text": "### Instruction\nCreate a function that takes in a string and counts the number of vowels in it\n\n### Response\ndef count_vowels(string):\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n count = 0\n for char in string:\n if char in vowels:\n count += 1\n return count", "source_id": ""}{"text": "### Instruction\nWrite a function that takes in a string and returns a list of all the words that have more than 5 characters\n\n### Response\ndef long_words(string):\n words = string.split()\n long_words_list = []\n for word in words:\n if len(word) > 5:\n long_words_list.append(word)\n return long_words_list", "source_id": ""}{"text": "### Instruction\nCreate a function that takes in a string and replaces all punctuation with a space\n\n### Response\nimport string\n\ndef replace_punctuation(string):\n for char in string:\n if char in string.punctuation:\n string = string.replace(char, \" \")\n return string", "source_id": ""}{"text": "### Instruction\nCreate a function that takes in a list of numbers and returns true if the list contains at least one positive number\n\n### Response\ndef is_positive_number(numbers):\n for num in numbers:\n if num > 0:\n return True\n return False", "source_id": ""}{"text": "### Instruction\nWrite code in Java to generate the Fibonacci sequence up to N numbers.\n\n### Response\npublic class Fibonacci { \n \n public static void FibonacciN(int n) { \n int i, f=0, s=1; \n \n if (n == 1) \n System.out.print(f+ \" \"); \n \n else { \n System.out.print(f+\" \"+s+\" \"); \n \n for (i = 2; i < n; i++) { \n int next = f + s; \n System.out.print(next+\" \"); \n f= s; \n s = next; \n } \n } \n } \n}", "source_id": ""}{"text": "### Instruction\nWrite an algorithm to find the largest element in an array.\n\n### Response\n// Algorithm to find the largest element in an array\n\n// Step 1: Create a variable 'max' and initialize it with value of the first element in the array\nint max = arr[0];\n\n// Step 2: Iterate through the array and compare each element with 'max'\nfor (int i = 1; i < arr.length; i++) {\n if (arr[i] > max) {\n max = arr[i];\n }\n}\n\n// Step 3: Return the value of 'max'\nreturn max;", "source_id": ""}{"text": "### Instruction\nWrite code in Java to sort an array of integers in ascending order.\n\n### Response\npublic static void sortAscending(int[] arr) {\n for(int i = 0; i < arr.length - 1; i++) {\n int min = i;\n for (int j = i + 1; j < arr.length; j++) {\n if (arr[j] < arr[min]) {\n min = j;\n }\n }\n int tmp = arr[i];\n arr[i] = arr[min];\n arr[min] = tmp;\n }\n}", "source_id": ""}{"text": "### Instruction\nCreate a new button using HTML.\n\n### Response\n<button>My Button</button>", "source_id": ""}{"text": "### Instruction\nWrite a SQL query to add a new column \"age\" in the employees table.\n\n### Response\nALTER TABLE Employees\nADD COLUMN age INT;", "source_id": ""}{"text": "### Instruction\nDesign a function in Python to delete duplicates from a list.\n\n### Response\ndef remove_duplicates(list): \n \n unique_list = [] \n \n for x in list: \n if x not in unique_list: \n unique_list.append(x) \n return unique_list \n \nlist = [2, 3, 2, 4, 5, 5, 6] \nprint (\"Original List: \", list) \nprint (\"Unique List: \", remove_duplicates(list)) \n\nOutput: \nOriginal List: [2, 3, 2, 4, 5, 5, 6]\nUnique List: [2, 3, 4, 5, 6]", "source_id": ""}{"text": "### Instruction\nImplement an algorithm to find the sum of all the elements in an array.\n\n### Response\n// Algorithm to calculate the sum of all the elements in an array\n\n// Step 1: Initialize a variable 'sum' and set it equal to 0\nint sum = 0;\n\n// Step 2: Iterate through the array and add each element to 'sum'\nfor (int i = 0; i < arr.length; i++) {\n sum += arr[i];\n}\n\n// Step 3: Return the value of sum\nreturn sum;", "source_id": ""}{"text": "### Instruction\nWrite a MySQL query to display the name, job and salary of all employees.\n\n### Response\nSELECT name, job, salary \nFROM employees;", "source_id": ""}{"text": "### Instruction\nFind the sum of two numbers using C#.\n\n### Response\nint result = 123 + 456;\nConsole.WriteLine(result); //Output: 579", "source_id": ""}{"text": "### Instruction\nCreate a web page using HTML and CSS that displays a div with some text.\n\n### Response\n<html>\n <head>\n <title>Div Example</title>\n </head>\n <body>\n <div>Hello, welcome to my website!</div>\n </body>\n</html>", "source_id": ""}{"text": "### Instruction\nWrite a JavaScript function to capitalize the first letter of each word in a string.\n\n### Response\nfunction capitalizeFirstLetter(str) {\n return str.replace(/\\w\\S*/g, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n}\ncapitalizeFirstLetter('This is an example');", "source_id": ""}{"text": "### Instruction\nWrite a Python program to loop through all the items in a given list.\n\n### Response\nmy_list = [1, 2, 3, 4, 5, 6]\nfor item in my_list:\n print(item)", "source_id": ""}{"text": "### Instruction\nWrite a SQL query to select the name and address from a given table.\n\n### Response\nSELECT name, address FROM Employee", "source_id": ""}{"text": "### Instruction\nCreate a new CSS animation rule to rotate an object a full circle.\n\n### Response\n@keyframes rotate {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n}", "source_id": ""}{"text": "### Instruction\nWrite a PL/SQL program to print out all numbers from 1 to 10.\n\n### Response\nBEGIN\n FOR i IN 1..10 LOOP\n DBMS_OUTPUT.PUT_LINE(i);\n END LOOP;\nEND;", "source_id": ""}{"text": "### Instruction\nWrite a JavaScript code snippet to remove the last element from an array.\n\n### Response\nlet array = [1, 2, 3, 4, 5];\narray.pop(); // remove the last element\nconsole.log(array); // [1, 2, 3, 4]", "source_id": ""}{"text": "### Instruction\nConvert the following binary number to a decimal number.\n\n### Response\n19 (10011 = 2^4 + 2^3 + 2^1 = 16 + 8 + 1 = 25)", "source_id": ""}{"text": "### Instruction\nWrite a Java program to calculate the sum of the two given integers.\n\n### Response\npublic static int addIntegers(int a, int b) {\n int sum = a + b;\n return sum;\n}\n\npublic static void main(String[] args) {\n int x = 4, y = 9;\n int sum = addIntegers(x, y);\n System.out.println(\"Sum is: \"+sum);\n}", "source_id": ""}{"text": "### Instruction\nWhat is the largest prime factor of the number 885?\n\n### Response\nThe largest prime factor of 885 is 5.", "source_id": ""}{"text": "### Instruction\nCreate a function in Python which takes two parameters and returns their product.\n\n### Response\ndef product(a, b):\n return a*b", "source_id": ""}{"text": "### Instruction\nConstruct a for loop that prints out the numbers from 1 to 10\n\n### Response\nfor i in range(1, 11):\n print(i)", "source_id": ""}{"text": "### Instruction\nCreate an HTML form with three input fields: firstName, lastName and age.\n\n### Response\n<form> \n First Name:<br> \n <input type=\"text\" name=\"firstName\"><br> \n Last Name:<br> \n <input type=\"text\" name=\"lastName\"><br> \n Age:<br> \n <input type=\"number\" name=\"age\"><br><br> \n <input type=\"submit\" value=\"Submit\"> \n</form>", "source_id": ""}{"text": "### Instruction\nWrite a function in Java that takes two strings as parameters and returns true if the first string is a substring of the second.\n\n### Response\npublic boolean isSubstring(String s1, String s2) \n{ \n int M = s1.length(); \n int N = s2.length(); \n \n for (int i = 0; i <= N - M; i++) { \n int j; \n \n for (j = 0; j < M; j++) \n if (s2.charAt(i + j) != s1.charAt(j)) \n break; \n \n if (j == M) \n return true; \n } \n \n return false; \n}", "source_id": ""}{"text": "### Instruction\nConstruct a while loop that increments a counter every time a number is divisible by 3.\n\n### Response\nint count = 0; \nint i = 0; \nwhile(i < 100)\n{\n if(i % 3 == 0)\n count++; \n i++;\n}", "source_id": ""}{"text": "### Instruction\nCreate a Regular Expression pattern to find words that contain the letters \"a\", \"b\", and \"c\".\n\n### Response\n\\b[abc]+\\w*\\b", "source_id": ""}{"text": "### Instruction\nCreate a class in Python to represent a Person.\n\n### Response\nclass Person:\n # Constructor \n def __init__(self, name, age): \n \n # instance attributes \n self.name = name \n self.age = age \n \n # instance method \n def greeting(self): \n print(\"My name is\", self.name) \n \n# construct an object \nperson1 = Person(\"John\", 36) \n \n# call a method of the object \nperson1.greeting()", "source_id": ""}{"text": "### Instruction\nWrite a code to check whether the input string is a palindrome or not.\n\n### Response\n\"\"\"\nWrite a code to check whether the input string is a palindrome or not\n\"\"\"\n\ndef check_palindrome(input_string):\n rev_str = input_string[::-1]\n \n # Checking if both string are equal or not\n if rev_str == input_string:\n return True\n return False\n \n# main function\nif __name__ == \"__main__\":\n str = \"a man a plan a canal panama\"\n if check_palindrome(str):\n print(\"String is Palindrome\")\n else:\n print(\"String is not Palindrome\")", "source_id": ""}{"text": "### Instruction\nWrite a code to remove the duplicates from a given list.\n\n### Response\n\"\"\"\nWrite a code to remove the duplicates from a given list\n\"\"\"\n\n# List containing the elements\nmylist = [1,2,3,1,2]\n\n# Creating a new list with unique elements\nunique_list = list(set(mylist))\n\n# Printing the new list\nprint(\"New list with unique elements is {}\".format(unique_list))", "source_id": ""}{"text": "### Instruction\nCreate a dictionary containing the key-value pair of a given string.\n\n### Response\n\"\"\"\nCreate a dictionary containing the key-value pair of a given string\n\"\"\"\n\n# Given string\nstring = \"test string\"\n\n# Initialising an empty dictionary\nmy_dict = {}\n\n# Looping through the given string\nfor char in string:\n # If the character is not already in dictionary\n if char not in my_dict:\n # Adding the character to the dictionary\n my_dict[char] = 1\n # If the character already exists in dictionary\n else:\n # Incrementing the frequency\n my_dict[char] += 1\n \n# Printing the dictionary\nprint(my_dict)", "source_id": ""}{"text": "### Instruction\nWrite a code to generate a random number between 1 to 10.\n\n### Response\n\"\"\"\nWrite a code to generate a random number between 1 to 10\n\"\"\"\n\nimport random\n\n# Generate random number between 1 to 10 \nrandom_number = random.randint(1,10)\n\n# Printing the random number\nprint(random_number)", "source_id": ""}{"text": "### Instruction\nWrite a code to create a 3 x 3 matrix containing all 0s.\n\n### Response\n\"\"\"\nWrite a code to create a 3 x 3 matrix containing all 0s\n\"\"\"\n\n# Creating an empty 3 x 3 matrix\nmatrix = [[0 for x in range(3)] for y in range(3)] \n \n# Printing the matrix\nprint(matrix)", "source_id": ""}123456789101112131415161718{ "id": "cortex-code-sft", "source": "sahil2801/CodeAlpaca-20k", "config": "default", "split": "train", "origin": "Hugging Face Hub dataset repository sahil2801/CodeAlpaca-20k", "license": "cc-by-4.0", "license_url": "https://huggingface.co/datasets/sahil2801/CodeAlpaca-20k", "redistribution": "yes", "attribution": "CodeAlpaca-20k, distributed under CC BY 4.0. Attribution required: cite the dataset repository above when redistributing.", "record_type": "code-sft", "rows_fetched": 200, "records_written": 200, "jsonl_sha256": "1c9bffb3a800f5735978d9f82f3f42558cd36d5188c2486718003a96f5a1ceda", "jsonl_bytes": 69677, "note": "Instruction/response pairs for code generation. CC BY 4.0 permits redistribution and commercial use with attribution.", "fetched_via": "https://datasets-server.huggingface.co/rows"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200{"text": "### Instruction\nWrite a python function to remove first and last occurrence of a given character from the string.\n\n### Response\ndef remove_Occ(s,ch): \r\n for i in range(len(s)): \r\n if (s[i] == ch): \r\n s = s[0 : i] + s[i + 1:] \r\n break\r\n for i in range(len(s) - 1,-1,-1): \r\n if (s[i] == ch): \r\n s = s[0 : i] + s[i + 1:] \r\n break\r\n return s ", "source_id": "11"}{"text": "### Instruction\nWrite a function to sort a given matrix in ascending order according to the sum of its rows.\n\n### Response\ndef sort_matrix(M):\r\n result = sorted(M, key=sum)\r\n return result", "source_id": "12"}{"text": "### Instruction\nWrite a function to count the most common words in a dictionary.\n\n### Response\nfrom collections import Counter\r\ndef count_common(words):\r\n word_counts = Counter(words)\r\n top_four = word_counts.most_common(4)\r\n return (top_four)\r\n", "source_id": "13"}{"text": "### Instruction\nWrite a python function to find the volume of a triangular prism.\n\n### Response\ndef find_Volume(l,b,h) : \r\n return ((l * b * h) / 2) ", "source_id": "14"}{"text": "### Instruction\nWrite a function to split a string at lowercase letters.\n\n### Response\nimport re\r\ndef split_lowerstring(text):\r\n return (re.findall('[a-z][^a-z]*', text))", "source_id": "15"}{"text": "### Instruction\nWrite a function to find sequences of lowercase letters joined with an underscore.\n\n### Response\nimport re\r\ndef text_lowercase_underscore(text):\r\n patterns = '^[a-z]+_[a-z]+$'\r\n if re.search(patterns, text):\r\n return 'Found a match!'\r\n else:\r\n return('Not matched!')", "source_id": "16"}{"text": "### Instruction\nWrite a function to find the perimeter of a square.\n\n### Response\ndef square_perimeter(a):\r\n perimeter=4*a\r\n return perimeter", "source_id": "17"}{"text": "### Instruction\nWrite a function to remove characters from the first string which are present in the second string.\n\n### Response\nNO_OF_CHARS = 256\r\ndef str_to_list(string): \r\n\ttemp = [] \r\n\tfor x in string: \r\n\t\ttemp.append(x) \r\n\treturn temp \r\ndef lst_to_string(List): \r\n\treturn ''.join(List) \r\ndef get_char_count_array(string): \r\n\tcount = [0] * NO_OF_CHARS \r\n\tfor i in string: \r\n\t\tcount[ord(i)] += 1\r\n\treturn count \r\ndef remove_dirty_chars(string, second_string): \r\n\tcount = get_char_count_array(second_string) \r\n\tip_ind = 0\r\n\tres_ind = 0\r\n\ttemp = '' \r\n\tstr_list = str_to_list(string) \r\n\twhile ip_ind != len(str_list): \r\n\t\ttemp = str_list[ip_ind] \r\n\t\tif count[ord(temp)] == 0: \r\n\t\t\tstr_list[res_ind] = str_list[ip_ind] \r\n\t\t\tres_ind += 1\r\n\t\tip_ind+=1\r\n\treturn lst_to_string(str_list[0:res_ind]) ", "source_id": "18"}{"text": "### Instruction\nWrite a function to find whether a given array of integers contains any duplicate element.\n\n### Response\ndef test_duplicate(arraynums):\r\n nums_set = set(arraynums) \r\n return len(arraynums) != len(nums_set) ", "source_id": "19"}{"text": "### Instruction\nWrite a function to check if the given number is woodball or not.\n\n### Response\ndef is_woodall(x): \r\n\tif (x % 2 == 0): \r\n\t\treturn False\r\n\tif (x == 1): \r\n\t\treturn True\r\n\tx = x + 1 \r\n\tp = 0\r\n\twhile (x % 2 == 0): \r\n\t\tx = x/2\r\n\t\tp = p + 1\r\n\t\tif (p == x): \r\n\t\t\treturn True\r\n\treturn False", "source_id": "20"}{"text": "### Instruction\nWrite a function to find m number of multiples of n.\n\n### Response\ndef multiples_of_num(m,n): \r\n multiples_of_num= list(range(n,(m+1)*n, n)) \r\n return list(multiples_of_num)", "source_id": "21"}{"text": "### Instruction\nWrite a function to find the first duplicate element in a given array of integers.\n\n### Response\ndef find_first_duplicate(nums):\r\n num_set = set()\r\n no_duplicate = -1\r\n\r\n for i in range(len(nums)):\r\n\r\n if nums[i] in num_set:\r\n return nums[i]\r\n else:\r\n num_set.add(nums[i])\r\n\r\n return no_duplicate", "source_id": "22"}{"text": "### Instruction\nWrite a python function to find the maximum sum of elements of list in a list of lists.\n\n### Response\ndef maximum_Sum(list1): \r\n maxi = -100000\r\n for x in list1: \r\n sum = 0 \r\n for y in x: \r\n sum+= y \r\n maxi = max(sum,maxi) \r\n return maxi ", "source_id": "23"}{"text": "### Instruction\nWrite a function to convert the given binary number to its decimal equivalent.\n\n### Response\ndef binary_to_decimal(binary): \r\n binary1 = binary \r\n decimal, i, n = 0, 0, 0\r\n while(binary != 0): \r\n dec = binary % 10\r\n decimal = decimal + dec * pow(2, i) \r\n binary = binary//10\r\n i += 1\r\n return (decimal)", "source_id": "24"}{"text": "### Instruction\nWrite a python function to find the product of non-repeated elements in a given array.\n\n### Response\ndef find_Product(arr,n): \r\n arr.sort() \r\n prod = 1\r\n for i in range(0,n,1): \r\n if (arr[i - 1] != arr[i]): \r\n prod = prod * arr[i] \r\n return prod; ", "source_id": "25"}{"text": "### Instruction\nWrite a function to check if the given tuple list has all k elements.\n\n### Response\ndef check_k_elements(test_list, K):\r\n res = True\r\n for tup in test_list:\r\n for ele in tup:\r\n if ele != K:\r\n res = False\r\n return (res) ", "source_id": "26"}{"text": "### Instruction\nWrite a python function to remove all digits from a list of strings.\n\n### Response\nimport re \r\ndef remove(list): \r\n pattern = '[0-9]'\r\n list = [re.sub(pattern, '', i) for i in list] \r\n return list", "source_id": "27"}{"text": "### Instruction\nWrite a python function to find binomial co-efficient.\n\n### Response\ndef binomial_Coeff(n,k): \r\n if k > n : \r\n return 0\r\n if k==0 or k ==n : \r\n return 1 \r\n return binomial_Coeff(n-1,k-1) + binomial_Coeff(n-1,k) ", "source_id": "28"}{"text": "### Instruction\nWrite a python function to find the element occurring odd number of times.\n\n### Response\ndef get_Odd_Occurrence(arr,arr_size): \r\n for i in range(0,arr_size): \r\n count = 0\r\n for j in range(0,arr_size): \r\n if arr[i] == arr[j]: \r\n count+=1 \r\n if (count % 2 != 0): \r\n return arr[i] \r\n return -1", "source_id": "29"}{"text": "### Instruction\nWrite a python function to count all the substrings starting and ending with same characters.\n\n### Response\ndef check_Equality(s): \r\n return (ord(s[0]) == ord(s[len(s) - 1])); \r\ndef count_Substring_With_Equal_Ends(s): \r\n result = 0; \r\n n = len(s); \r\n for i in range(n): \r\n for j in range(1,n-i+1): \r\n if (check_Equality(s[i:i+j])): \r\n result+=1; \r\n return result; ", "source_id": "30"}{"text": "### Instruction\nWrite a function to find the top k integers that occur most frequently from given lists of sorted and distinct integers using heap queue algorithm.\n\n### Response\ndef func(nums, k):\r\n import collections\r\n d = collections.defaultdict(int)\r\n for row in nums:\r\n for i in row:\r\n d[i] += 1\r\n temp = []\r\n import heapq\r\n for key, v in d.items():\r\n if len(temp) < k:\r\n temp.append((v, key))\r\n if len(temp) == k:\r\n heapq.heapify(temp)\r\n else:\r\n if v > temp[0][0]:\r\n heapq.heappop(temp)\r\n heapq.heappush(temp, (v, key))\r\n result = []\r\n while temp:\r\n v, key = heapq.heappop(temp)\r\n result.append(key)\r\n return result", "source_id": "31"}{"text": "### Instruction\nWrite a python function to find the largest prime factor of a given number.\n\n### Response\nimport math \r\ndef max_Prime_Factors (n): \r\n maxPrime = -1 \r\n while n%2 == 0: \r\n maxPrime = 2\r\n n >>= 1 \r\n for i in range(3,int(math.sqrt(n))+1,2): \r\n while n % i == 0: \r\n maxPrime = i \r\n n = n / i \r\n if n > 2: \r\n maxPrime = n \r\n return int(maxPrime)", "source_id": "32"}{"text": "### Instruction\nWrite a python function to convert a decimal number to binary number.\n\n### Response\ndef decimal_To_Binary(N): \r\n B_Number = 0\r\n cnt = 0\r\n while (N != 0): \r\n rem = N % 2\r\n c = pow(10,cnt) \r\n B_Number += rem*c \r\n N //= 2 \r\n cnt += 1\r\n return B_Number ", "source_id": "33"}{"text": "### Instruction\nWrite a python function to find the missing number in a sorted array.\n\n### Response\ndef find_missing(ar,N): \r\n l = 0\r\n r = N - 1\r\n while (l <= r): \r\n mid = (l + r) / 2\r\n mid= int (mid) \r\n if (ar[mid] != mid + 1 and ar[mid - 1] == mid): \r\n return (mid + 1) \r\n elif (ar[mid] != mid + 1): \r\n r = mid - 1 \r\n else: \r\n l = mid + 1\r\n return (-1) ", "source_id": "34"}{"text": "### Instruction\nWrite a function to find the n-th rectangular number.\n\n### Response\ndef find_rect_num(n):\r\n return n*(n + 1) ", "source_id": "35"}{"text": "### Instruction\nWrite a python function to find the nth digit in the proper fraction of two given numbers.\n\n### Response\ndef find_Nth_Digit(p,q,N) : \r\n while (N > 0) : \r\n N -= 1; \r\n p *= 10; \r\n res = p // q; \r\n p %= q; \r\n return res; ", "source_id": "36"}{"text": "### Instruction\nWrite a function to sort a given mixed list of integers and strings.\n\n### Response\ndef sort_mixed_list(mixed_list):\r\n int_part = sorted([i for i in mixed_list if type(i) is int])\r\n str_part = sorted([i for i in mixed_list if type(i) is str])\r\n return int_part + str_part", "source_id": "37"}{"text": "### Instruction\nWrite a function to find the division of first even and odd number of a given list.\n\n### Response\ndef div_even_odd(list1):\r\n first_even = next((el for el in list1 if el%2==0),-1)\r\n first_odd = next((el for el in list1 if el%2!=0),-1)\r\n return (first_even/first_odd)", "source_id": "38"}{"text": "### Instruction\nWrite a function to check if the letters of a given string can be rearranged so that two characters that are adjacent to each other are different.\n\n### Response\nimport heapq\r\nfrom collections import Counter\r\ndef rearange_string(S):\r\n ctr = Counter(S)\r\n heap = [(-value, key) for key, value in ctr.items()]\r\n heapq.heapify(heap)\r\n if (-heap[0][0]) * 2 > len(S) + 1: \r\n return \"\"\r\n ans = []\r\n while len(heap) >= 2:\r\n nct1, char1 = heapq.heappop(heap)\r\n nct2, char2 = heapq.heappop(heap)\r\n ans.extend([char1, char2])\r\n if nct1 + 1: heapq.heappush(heap, (nct1 + 1, char1))\r\n if nct2 + 1: heapq.heappush(heap, (nct2 + 1, char2))\r\n return \"\".join(ans) + (heap[0][1] if heap else \"\")", "source_id": "39"}{"text": "### Instruction\nWrite a function to find frequency of the elements in a given list of lists using collections module.\n\n### Response\nfrom collections import Counter\r\nfrom itertools import chain\r\ndef freq_element(nums):\r\n result = Counter(chain.from_iterable(nums))\r\n return result", "source_id": "40"}{"text": "### Instruction\nWrite a function to filter even numbers using lambda function.\n\n### Response\ndef filter_evennumbers(nums):\r\n even_nums = list(filter(lambda x: x%2 == 0, nums))\r\n return even_nums", "source_id": "41"}{"text": "### Instruction\nWrite a python function to find the sum of repeated elements in a given array.\n\n### Response\ndef find_Sum(arr,n): \r\n return sum([x for x in arr if arr.count(x) > 1])", "source_id": "42"}{"text": "### Instruction\nWrite a function to find sequences of lowercase letters joined with an underscore using regex.\n\n### Response\nimport re\r\ndef text_match(text):\r\n patterns = '^[a-z]+_[a-z]+$'\r\n if re.search(patterns, text):\r\n return ('Found a match!')\r\n else:\r\n return ('Not matched!')", "source_id": "43"}{"text": "### Instruction\nWrite a function that matches a word at the beginning of a string.\n\n### Response\nimport re\r\ndef text_match_string(text):\r\n patterns = '^\\w+'\r\n if re.search(patterns, text):\r\n return 'Found a match!'\r\n else:\r\n return 'Not matched!'", "source_id": "44"}{"text": "### Instruction\nWrite a function to find the gcd of the given array elements.\n\n### Response\ndef find_gcd(x, y): \r\n\twhile(y): \r\n\t\tx, y = y, x % y \r\n\treturn x \r\ndef get_gcd(l):\r\n num1 = l[0]\r\n num2 = l[1]\r\n gcd = find_gcd(num1, num2)\r\n for i in range(2, len(l)):\r\n gcd = find_gcd(gcd, l[i])\r\n return gcd", "source_id": "45"}{"text": "### Instruction\nWrite a python function to determine whether all the numbers are different from each other are not.\n\n### Response\ndef test_distinct(data):\r\n if len(data) == len(set(data)):\r\n return True\r\n else:\r\n return False;", "source_id": "46"}{"text": "### Instruction\nWrite a python function to find the last digit when factorial of a divides factorial of b.\n\n### Response\ndef compute_Last_Digit(A,B): \r\n variable = 1\r\n if (A == B): \r\n return 1\r\n elif ((B - A) >= 5): \r\n return 0\r\n else: \r\n for i in range(A + 1,B + 1): \r\n variable = (variable * (i % 10)) % 10\r\n return variable % 10", "source_id": "47"}{"text": "### Instruction\nWrite a python function to set all odd bits of a given number.\n\n### Response\ndef odd_bit_set_number(n):\r\n count = 0;res = 0;temp = n\r\n while temp > 0:\r\n if count % 2 == 0:\r\n res |= (1 << count)\r\n count += 1\r\n temp >>= 1\r\n return (n | res)", "source_id": "48"}{"text": "### Instruction\nWrite a function to extract every first or specified element from a given two-dimensional list.\n\n### Response\ndef specified_element(nums, N):\r\n result = [i[N] for i in nums]\r\n return result\r\n ", "source_id": "49"}{"text": "### Instruction\nWrite a function to find the list with minimum length using lambda function.\n\n### Response\ndef min_length_list(input_list):\r\n min_length = min(len(x) for x in input_list ) \r\n min_list = min(input_list, key = lambda i: len(i))\r\n return(min_length, min_list)", "source_id": "50"}{"text": "### Instruction\nWrite a function to print check if the triangle is equilateral or not.\n\n### Response\ndef check_equilateral(x,y,z):\r\n if x == y == z:\r\n\t return True\r\n else:\r\n return False", "source_id": "51"}{"text": "### Instruction\nWrite a function to caluclate area of a parallelogram.\n\n### Response\ndef parallelogram_area(b,h):\r\n area=b*h\r\n return area", "source_id": "52"}{"text": "### Instruction\nWrite a python function to check whether the first and last characters of a given string are equal or not.\n\n### Response\ndef check_Equality(str):\r\n if (str[0] == str[-1]): \r\n return (\"Equal\") \r\n else: \r\n return (\"Not Equal\") ", "source_id": "53"}{"text": "### Instruction\nWrite a function to sort the given array by using counting sort.\n\n### Response\ndef counting_sort(my_list):\r\n max_value = 0\r\n for i in range(len(my_list)):\r\n if my_list[i] > max_value:\r\n max_value = my_list[i]\r\n buckets = [0] * (max_value + 1)\r\n for i in my_list:\r\n buckets[i] += 1\r\n i = 0\r\n for j in range(max_value + 1):\r\n for a in range(buckets[j]):\r\n my_list[i] = j\r\n i += 1\r\n return my_list", "source_id": "54"}{"text": "### Instruction\nWrite a function to find t-nth term of geometric series.\n\n### Response\nimport math\r\ndef tn_gp(a,n,r):\r\n tn = a * (math.pow(r, n - 1))\r\n return tn", "source_id": "55"}{"text": "### Instruction\nWrite a python function to check if a given number is one less than twice its reverse.\n\n### Response\ndef rev(num): \r\n rev_num = 0\r\n while (num > 0): \r\n rev_num = (rev_num * 10 + num % 10) \r\n num = num // 10 \r\n return rev_num \r\ndef check(n): \r\n return (2 * rev(n) == n + 1) ", "source_id": "56"}{"text": "### Instruction\nWrite a python function to find the largest number that can be formed with the given digits.\n\n### Response\ndef find_Max_Num(arr,n) : \r\n arr.sort(reverse = True) \r\n num = arr[0] \r\n for i in range(1,n) : \r\n num = num * 10 + arr[i] \r\n return num ", "source_id": "57"}{"text": "### Instruction\nWrite a python function to check whether the given two integers have opposite sign or not.\n\n### Response\ndef opposite_Signs(x,y): \r\n return ((x ^ y) < 0); ", "source_id": "58"}{"text": "### Instruction\nWrite a function to find the nth octagonal number.\n\n### Response\ndef is_octagonal(n): \r\n\treturn 3 * n * n - 2 * n ", "source_id": "59"}{"text": "### Instruction\nWrite a function to find the maximum length of the subsequence with difference between adjacent elements for the given array.\n\n### Response\ndef max_len_sub( arr, n): \r\n\tmls=[] \r\n\tmax = 0\r\n\tfor i in range(n): \r\n\t\tmls.append(1) \r\n\tfor i in range(n): \r\n\t\tfor j in range(i): \r\n\t\t\tif (abs(arr[i] - arr[j]) <= 1 and mls[i] < mls[j] + 1): \r\n\t\t\t\tmls[i] = mls[j] + 1\r\n\tfor i in range(n): \r\n\t\tif (max < mls[i]): \r\n\t\t\tmax = mls[i] \r\n\treturn max", "source_id": "60"}{"text": "### Instruction\nWrite a python function to count number of substrings with the sum of digits equal to their length.\n\n### Response\nfrom collections import defaultdict\r\ndef count_Substrings(s,n):\r\n count,sum = 0,0\r\n mp = defaultdict(lambda : 0)\r\n mp[0] += 1\r\n for i in range(n):\r\n sum += ord(s[i]) - ord('0')\r\n count += mp[sum - (i + 1)]\r\n mp[sum - (i + 1)] += 1\r\n return count", "source_id": "61"}{"text": "### Instruction\nWrite a python function to find smallest number in a list.\n\n### Response\ndef smallest_num(xs):\n return min(xs)\n", "source_id": "62"}{"text": "### Instruction\nWrite a function to find the maximum difference between available pairs in the given tuple list.\n\n### Response\ndef max_difference(test_list):\r\n temp = [abs(b - a) for a, b in test_list]\r\n res = max(temp)\r\n return (res) ", "source_id": "63"}{"text": "### Instruction\nWrite a function to sort a list of tuples using lambda.\n\n### Response\ndef subject_marks(subjectmarks):\r\n#subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)])\r\n subjectmarks.sort(key = lambda x: x[1])\r\n return subjectmarks", "source_id": "64"}{"text": "### Instruction\nWrite a function of recursion list sum.\n\n### Response\ndef recursive_list_sum(data_list):\r\n\ttotal = 0\r\n\tfor element in data_list:\r\n\t\tif type(element) == type([]):\r\n\t\t\ttotal = total + recursive_list_sum(element)\r\n\t\telse:\r\n\t\t\ttotal = total + element\r\n\treturn total", "source_id": "65"}{"text": "### Instruction\nWrite a python function to count positive numbers in a list.\n\n### Response\ndef pos_count(list):\r\n pos_count= 0\r\n for num in list: \r\n if num >= 0: \r\n pos_count += 1\r\n return pos_count ", "source_id": "66"}{"text": "### Instruction\nWrite a function to find the number of ways to partition a set of bell numbers.\n\n### Response\ndef bell_number(n): \r\n bell = [[0 for i in range(n+1)] for j in range(n+1)] \r\n bell[0][0] = 1\r\n for i in range(1, n+1): \r\n bell[i][0] = bell[i-1][i-1] \r\n for j in range(1, i+1): \r\n bell[i][j] = bell[i-1][j-1] + bell[i][j-1] \r\n return bell[n][0] ", "source_id": "67"}{"text": "### Instruction\nWrite a python function to check whether the given array is monotonic or not.\n\n### Response\ndef is_Monotonic(A): \r\n return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or\r\n all(A[i] >= A[i + 1] for i in range(len(A) - 1))) ", "source_id": "68"}{"text": "### Instruction\nWrite a function to check whether a list contains the given sublist or not.\n\n### Response\ndef is_sublist(l, s):\r\n\tsub_set = False\r\n\tif s == []:\r\n\t\tsub_set = True\r\n\telif s == l:\r\n\t\tsub_set = True\r\n\telif len(s) > len(l):\r\n\t\tsub_set = False\r\n\telse:\r\n\t\tfor i in range(len(l)):\r\n\t\t\tif l[i] == s[0]:\r\n\t\t\t\tn = 1\r\n\t\t\t\twhile (n < len(s)) and (l[i+n] == s[n]):\r\n\t\t\t\t\tn += 1\t\t\t\t\r\n\t\t\t\tif n == len(s):\r\n\t\t\t\t\tsub_set = True\r\n\treturn sub_set", "source_id": "69"}{"text": "### Instruction\nWrite a function to find whether all the given tuples have equal length or not.\n\n### Response\ndef find_equal_tuple(Input, k):\r\n flag = 1\r\n for tuple in Input:\r\n if len(tuple) != k:\r\n flag = 0\r\n break\r\n return flag\r\ndef get_equal(Input, k):\r\n if find_equal_tuple(Input, k) == 1:\r\n return (\"All tuples have same length\")\r\n else:\r\n return (\"All tuples do not have same length\")", "source_id": "70"}{"text": "### Instruction\nWrite a function to sort a list of elements using comb sort.\n\n### Response\ndef comb_sort(nums):\r\n shrink_fact = 1.3\r\n gaps = len(nums)\r\n swapped = True\r\n i = 0\r\n while gaps > 1 or swapped:\r\n gaps = int(float(gaps) / shrink_fact)\r\n swapped = False\r\n i = 0\r\n while gaps + i < len(nums):\r\n if nums[i] > nums[i+gaps]:\r\n nums[i], nums[i+gaps] = nums[i+gaps], nums[i]\r\n swapped = True\r\n i += 1\r\n return nums", "source_id": "71"}{"text": "### Instruction\nWrite a python function to check whether the given number can be represented as difference of two squares or not.\n\n### Response\ndef dif_Square(n): \r\n if (n % 4 != 2): \r\n return True\r\n return False", "source_id": "72"}{"text": "### Instruction\nWrite a function to split the given string with multiple delimiters by using regex.\n\n### Response\nimport re\r\ndef multiple_split(text):\r\n return (re.split('; |, |\\*|\\n',text))", "source_id": "73"}{"text": "### Instruction\nWrite a function to check whether it follows the sequence given in the patterns array.\n\n### Response\ndef is_samepatterns(colors, patterns): \r\n if len(colors) != len(patterns):\r\n return False \r\n sdict = {}\r\n pset = set()\r\n sset = set() \r\n for i in range(len(patterns)):\r\n pset.add(patterns[i])\r\n sset.add(colors[i])\r\n if patterns[i] not in sdict.keys():\r\n sdict[patterns[i]] = []\r\n\r\n keys = sdict[patterns[i]]\r\n keys.append(colors[i])\r\n sdict[patterns[i]] = keys\r\n\r\n if len(pset) != len(sset):\r\n return False \r\n\r\n for values in sdict.values():\r\n\r\n for i in range(len(values) - 1):\r\n if values[i] != values[i+1]:\r\n return False\r\n\r\n return True", "source_id": "74"}{"text": "### Instruction\nWrite a function to find tuples which have all elements divisible by k from the given list of tuples.\n\n### Response\ndef find_tuples(test_list, K):\r\n res = [sub for sub in test_list if all(ele % K == 0 for ele in sub)]\r\n return (str(res)) ", "source_id": "75"}{"text": "### Instruction\nWrite a python function to count the number of squares in a rectangle.\n\n### Response\ndef count_Squares(m,n):\r\n if(n < m):\r\n temp = m\r\n m = n\r\n n = temp\r\n return ((m * (m + 1) * (2 * m + 1) / 6 + (n - m) * m * (m + 1) / 2))", "source_id": "76"}{"text": "### Instruction\nWrite a python function to find the difference between sum of even and odd digits.\n\n### Response\ndef is_Diff(n): \r\n return (n % 11 == 0) ", "source_id": "77"}{"text": "### Instruction\nWrite a python function to find number of integers with odd number of set bits.\n\n### Response\ndef count_With_Odd_SetBits(n): \r\n if (n % 2 != 0): \r\n return (n + 1) / 2\r\n count = bin(n).count('1') \r\n ans = n / 2\r\n if (count % 2 != 0): \r\n ans += 1\r\n return ans ", "source_id": "78"}{"text": "### Instruction\nWrite a python function to check whether the length of the word is odd or not.\n\n### Response\ndef word_len(s): \r\n s = s.split(' ') \r\n for word in s: \r\n if len(word)%2!=0: \r\n return True \r\n else:\r\n return False", "source_id": "79"}{"text": "### Instruction\nWrite a function to find the nth tetrahedral number.\n\n### Response\ndef tetrahedral_number(n): \r\n\treturn (n * (n + 1) * (n + 2)) / 6", "source_id": "80"}{"text": "### Instruction\nWrite a function to zip the two given tuples.\n\n### Response\ndef zip_tuples(test_tup1, test_tup2):\r\n res = []\r\n for i, j in enumerate(test_tup1):\r\n res.append((j, test_tup2[i % len(test_tup2)])) \r\n return (res) ", "source_id": "81"}{"text": "### Instruction\nWrite a function to find the volume of a sphere.\n\n### Response\nimport math\r\ndef volume_sphere(r):\r\n volume=(4/3)*math.pi*r*r*r\r\n return volume", "source_id": "82"}{"text": "### Instruction\nWrite a python function to find the character made by adding all the characters of the given string.\n\n### Response\ndef get_Char(strr): \r\n summ = 0\r\n for i in range(len(strr)): \r\n summ += (ord(strr[i]) - ord('a') + 1) \r\n if (summ % 26 == 0): \r\n return ord('z') \r\n else: \r\n summ = summ % 26\r\n return chr(ord('a') + summ - 1)", "source_id": "83"}{"text": "### Instruction\nWrite a function to find the n-th number in newman conway sequence.\n\n### Response\ndef sequence(n): \r\n\tif n == 1 or n == 2: \r\n\t\treturn 1\r\n\telse: \r\n\t\treturn sequence(sequence(n-1)) + sequence(n-sequence(n-1))", "source_id": "84"}{"text": "### Instruction\nWrite a function to find the surface area of a sphere.\n\n### Response\nimport math\r\ndef surfacearea_sphere(r):\r\n surfacearea=4*math.pi*r*r\r\n return surfacearea", "source_id": "85"}{"text": "### Instruction\nWrite a function to find nth centered hexagonal number.\n\n### Response\ndef centered_hexagonal_number(n):\r\n return 3 * n * (n - 1) + 1", "source_id": "86"}{"text": "### Instruction\nWrite a function to merge three dictionaries into a single expression.\n\n### Response\nimport collections as ct\r\ndef merge_dictionaries_three(dict1,dict2, dict3):\r\n merged_dict = dict(ct.ChainMap({},dict1,dict2,dict3))\r\n return merged_dict", "source_id": "87"}{"text": "### Instruction\nWrite a function to get the frequency of the elements in a list.\n\n### Response\nimport collections\r\ndef freq_count(list1):\r\n freq_count= collections.Counter(list1)\r\n return freq_count", "source_id": "88"}{"text": "### Instruction\nWrite a function to find the closest smaller number than n.\n\n### Response\ndef closest_num(N):\r\n return (N - 1)", "source_id": "89"}{"text": "### Instruction\nWrite a python function to find the length of the longest word.\n\n### Response\ndef len_log(list1):\r\n max=len(list1[0])\r\n for i in list1:\r\n if len(i)>max:\r\n max=len(i)\r\n return max", "source_id": "90"}{"text": "### Instruction\nWrite a function to check if a substring is present in a given list of string values.\n\n### Response\ndef find_substring(str1, sub_str):\r\n if any(sub_str in s for s in str1):\r\n return True\r\n return False", "source_id": "91"}{"text": "### Instruction\nWrite a function to check whether the given number is undulating or not.\n\n### Response\ndef is_undulating(n): \r\n\tif (len(n) <= 2): \r\n\t\treturn False\r\n\tfor i in range(2, len(n)): \r\n\t\tif (n[i - 2] != n[i]): \r\n\t\t\treturn False\r\n\treturn True", "source_id": "92"}{"text": "### Instruction\nWrite a function to calculate the value of 'a' to the power 'b'.\n\n### Response\ndef power(a,b):\r\n\tif b==0:\r\n\t\treturn 1\r\n\telif a==0:\r\n\t\treturn 0\r\n\telif b==1:\r\n\t\treturn a\r\n\telse:\r\n\t\treturn a*power(a,b-1)", "source_id": "93"}{"text": "### Instruction\nWrite a function to extract the index minimum value record from the given tuples.\n\n### Response\nfrom operator import itemgetter \r\ndef index_minimum(test_list):\r\n res = min(test_list, key = itemgetter(1))[0]\r\n return (res) ", "source_id": "94"}{"text": "### Instruction\nWrite a python function to find the minimum length of sublist.\n\n### Response\ndef Find_Min_Length(lst): \r\n minLength = min(len(x) for x in lst )\r\n return minLength ", "source_id": "95"}{"text": "### Instruction\nWrite a python function to find the number of divisors of a given integer.\n\n### Response\ndef divisor(n):\r\n for i in range(n):\r\n x = len([i for i in range(1,n+1) if not n % i])\r\n return x", "source_id": "96"}{"text": "### Instruction\nWrite a function to find frequency count of list of lists.\n\n### Response\ndef frequency_lists(list1):\r\n list1 = [item for sublist in list1 for item in sublist]\r\n dic_data = {}\r\n for num in list1:\r\n if num in dic_data.keys():\r\n dic_data[num] += 1\r\n else:\r\n key = num\r\n value = 1\r\n dic_data[key] = value\r\n return dic_data\r\n", "source_id": "97"}{"text": "### Instruction\nWrite a function to multiply all the numbers in a list and divide with the length of the list.\n\n### Response\ndef multiply_num(numbers): \r\n total = 1\r\n for x in numbers:\r\n total *= x \r\n return total/len(numbers) ", "source_id": "98"}{"text": "### Instruction\nWrite a function to convert the given decimal number to its binary equivalent.\n\n### Response\ndef decimal_to_binary(n): \r\n return bin(n).replace(\"0b\",\"\") ", "source_id": "99"}{"text": "### Instruction\nWrite a function to find the next smallest palindrome of a specified number.\n\n### Response\nimport sys\r\ndef next_smallest_palindrome(num):\r\n numstr = str(num)\r\n for i in range(num+1,sys.maxsize):\r\n if str(i) == str(i)[::-1]:\r\n return i", "source_id": "100"}{"text": "### Instruction\nWrite a function to find the kth element in the given array.\n\n### Response\ndef kth_element(arr, n, k):\r\n for i in range(n):\r\n for j in range(0, n-i-1):\r\n if arr[j] > arr[j+1]:\r\n arr[j], arr[j+1] == arr[j+1], arr[j]\r\n return arr[k-1]", "source_id": "101"}{"text": "### Instruction\nWrite a function to convert snake case string to camel case string.\n\n### Response\ndef snake_to_camel(word):\r\n import re\r\n return ''.join(x.capitalize() or '_' for x in word.split('_'))", "source_id": "102"}{"text": "### Instruction\nWrite a function to find eulerian number a(n, m).\n\n### Response\ndef eulerian_num(n, m): \r\n\tif (m >= n or n == 0): \r\n\t\treturn 0 \r\n\tif (m == 0): \r\n\t\treturn 1 \r\n\treturn ((n - m) * eulerian_num(n - 1, m - 1) +(m + 1) * eulerian_num(n - 1, m))", "source_id": "103"}{"text": "### Instruction\nWrite a function to sort each sublist of strings in a given list of lists using lambda function.\n\n### Response\ndef sort_sublists(input_list):\r\n result = [sorted(x, key = lambda x:x[0]) for x in input_list] \r\n return result\r", "source_id": "104"}{"text": "### Instruction\nWrite a python function to count true booleans in the given list.\n\n### Response\ndef count(lst): \r\n return sum(lst) ", "source_id": "105"}{"text": "### Instruction\nWrite a function to add the given list to the given tuples.\n\n### Response\ndef add_lists(test_list, test_tup):\r\n res = tuple(list(test_tup) + test_list)\r\n return (res) ", "source_id": "106"}{"text": "### Instruction\nWrite a python function to count hexadecimal numbers for a given range.\n\n### Response\ndef count_Hexadecimal(L,R) : \r\n count = 0; \r\n for i in range(L,R + 1) : \r\n if (i >= 10 and i <= 15) : \r\n count += 1; \r\n elif (i > 15) : \r\n k = i; \r\n while (k != 0) : \r\n if (k % 16 >= 10) : \r\n count += 1; \r\n k = k // 16; \r\n return count; ", "source_id": "107"}{"text": "### Instruction\nWrite a function to merge multiple sorted inputs into a single sorted iterator using heap queue algorithm.\n\n### Response\nimport heapq\r\ndef merge_sorted_list(num1,num2,num3):\r\n num1=sorted(num1)\r\n num2=sorted(num2)\r\n num3=sorted(num3)\r\n result = heapq.merge(num1,num2,num3)\r\n return list(result)", "source_id": "108"}{"text": "### Instruction\nWrite a python function to find the count of rotations of a binary string with odd value.\n\n### Response\ndef odd_Equivalent(s,n): \r\n count=0\r\n for i in range(0,n): \r\n if (s[i] == '1'): \r\n count = count + 1\r\n return count ", "source_id": "109"}{"text": "### Instruction\nWrite a function to extract the ranges that are missing from the given list with the given start range and end range values.\n\n### Response\ndef extract_missing(test_list, strt_val, stop_val):\r\n res = []\r\n for sub in test_list:\r\n if sub[0] > strt_val:\r\n res.append((strt_val, sub[0]))\r\n strt_val = sub[1]\r\n if strt_val < stop_val:\r\n res.append((strt_val, stop_val))\r\n return (res) ", "source_id": "110"}{"text": "### Instruction\nWrite a function to find common elements in given nested lists. * list item * list item * list item * list item\n\n### Response\ndef common_in_nested_lists(nestedlist):\r\n result = list(set.intersection(*map(set, nestedlist)))\r\n return result", "source_id": "111"}{"text": "### Instruction\nWrite a python function to find the perimeter of a cylinder.\n\n### Response\ndef perimeter(diameter,height) : \r\n return 2*(diameter+height) ", "source_id": "112"}{"text": "### Instruction\nWrite a function to check if a string represents an integer or not.\n\n### Response\ndef check_integer(text):\r\n text = text.strip()\r\n if len(text) < 1:\r\n return None\r\n else:\r\n if all(text[i] in \"0123456789\" for i in range(len(text))):\r\n return True\r\n elif (text[0] in \"+-\") and \\\r\n all(text[i] in \"0123456789\" for i in range(1,len(text))):\r\n return True\r\n else:\r\n return False", "source_id": "113"}{"text": "### Instruction\nWrite a function to assign frequency to each tuple in the given tuple list.\n\n### Response\nfrom collections import Counter \r\ndef assign_freq(test_list):\r\n res = [(*key, val) for key, val in Counter(test_list).items()]\r\n return (str(res)) ", "source_id": "114"}{"text": "### Instruction\nWrite a function to check whether all dictionaries in a list are empty or not.\n\n### Response\ndef empty_dit(list1):\r\n empty_dit=all(not d for d in list1)\r\n return empty_dit", "source_id": "115"}{"text": "### Instruction\nWrite a function to convert a given tuple of positive integers into an integer.\n\n### Response\ndef tuple_to_int(nums):\r\n result = int(''.join(map(str,nums)))\r\n return result", "source_id": "116"}{"text": "### Instruction\nWrite a function to convert all possible convertible elements in the list to float.\n\n### Response\ndef list_to_float(test_list):\r\n res = []\r\n for tup in test_list:\r\n temp = []\r\n for ele in tup:\r\n if ele.isalpha():\r\n temp.append(ele)\r\n else:\r\n temp.append(float(ele))\r\n res.append((temp[0],temp[1])) \r\n return (str(res)) ", "source_id": "117"}{"text": "### Instruction\n[link text](https:// [link text](https:// [link text](https://)))write a function to convert a string to a list.\n\n### Response\ndef string_to_list(string): \r\n lst = list(string.split(\" \")) \r\n return lst", "source_id": "118"}{"text": "### Instruction\nWrite a python function to find the element that appears only once in a sorted array.\n\n### Response\ndef search(arr,n) :\r\n XOR = 0\r\n for i in range(n) :\r\n XOR = XOR ^ arr[i]\r\n return (XOR)", "source_id": "119"}{"text": "### Instruction\nWrite a function to find the maximum product from the pairs of tuples within a given list.\n\n### Response\ndef max_product_tuple(list1):\r\n result_max = max([abs(x * y) for x, y in list1] )\r\n return result_max", "source_id": "120"}{"text": "### Instruction\nWrite a function to find the triplet with sum of the given array\n\n### Response\ndef check_triplet(A, n, sum, count):\r\n if count == 3 and sum == 0:\r\n return True\r\n if count == 3 or n == 0 or sum < 0:\r\n return False\r\n return check_triplet(A, n - 1, sum - A[n - 1], count + 1) or\\\r\n check_triplet(A, n - 1, sum, count)", "source_id": "121"}{"text": "### Instruction\nWrite a function to find n’th smart number.\n\n### Response\nMAX = 3000 \r\ndef smartNumber(n): \r\n\tprimes = [0] * MAX \r\n\tresult = [] \r\n\tfor i in range(2, MAX): \r\n\t\tif (primes[i] == 0): \r\n\t\t\tprimes[i] = 1 \r\n\t\t\tj = i * 2 \r\n\t\t\twhile (j < MAX): \r\n\t\t\t\tprimes[j] -= 1 \r\n\t\t\t\tif ( (primes[j] + 3) == 0): \r\n\t\t\t\t\tresult.append(j) \r\n\t\t\t\tj = j + i \r\n\tresult.sort() \r\n\treturn result[n - 1] ", "source_id": "122"}{"text": "### Instruction\nWrite a function to sum all amicable numbers from 1 to a specified number.\n\n### Response\ndef amicable_numbers_sum(limit):\r\n if not isinstance(limit, int):\r\n return \"Input is not an integer!\"\r\n if limit < 1:\r\n return \"Input must be bigger than 0!\"\r\n amicables = set()\r\n for num in range(2, limit+1):\r\n if num in amicables:\r\n continue\r\n sum_fact = sum([fact for fact in range(1, num) if num % fact == 0])\r\n sum_fact2 = sum([fact for fact in range(1, sum_fact) if sum_fact % fact == 0])\r\n if num == sum_fact2 and num != sum_fact:\r\n amicables.add(num)\r\n amicables.add(sum_fact2)\r\n return sum(amicables)", "source_id": "123"}{"text": "### Instruction\nWrite a function to get the angle of a complex number.\n\n### Response\nimport cmath\r\ndef angle_complex(a,b):\r\n cn=complex(a,b)\r\n angle=cmath.phase(a+b)\r\n return angle", "source_id": "124"}{"text": "### Instruction\nWrite a function to find the maximum difference between the number of 0s and number of 1s in any sub-string of the given binary string.\n\n### Response\ndef find_length(string, n): \r\n\tcurrent_sum = 0\r\n\tmax_sum = 0\r\n\tfor i in range(n): \r\n\t\tcurrent_sum += (1 if string[i] == '0' else -1) \r\n\t\tif current_sum < 0: \r\n\t\t\tcurrent_sum = 0\r\n\t\tmax_sum = max(current_sum, max_sum) \r\n\treturn max_sum if max_sum else 0", "source_id": "125"}{"text": "### Instruction\nWrite a python function to find the sum of common divisors of two given numbers.\n\n### Response\ndef sum(a,b): \r\n sum = 0\r\n for i in range (1,min(a,b)): \r\n if (a % i == 0 and b % i == 0): \r\n sum += i \r\n return sum", "source_id": "126"}{"text": "### Instruction\nWrite a function to multiply two integers without using the * operator in python.\n\n### Response\ndef multiply_int(x, y):\r\n if y < 0:\r\n return -multiply_int(x, -y)\r\n elif y == 0:\r\n return 0\r\n elif y == 1:\r\n return x\r\n else:\r\n return x + multiply_int(x, y - 1)", "source_id": "127"}{"text": "### Instruction\nWrite a function to shortlist words that are longer than n from a given list of words.\n\n### Response\ndef long_words(n, str):\r\n word_len = []\r\n txt = str.split(\" \")\r\n for x in txt:\r\n if len(x) > n:\r\n word_len.append(x)\r\n return word_len\t", "source_id": "128"}{"text": "### Instruction\nWrite a function to calculate magic square.\n\n### Response\ndef magic_square_test(my_matrix):\r\n iSize = len(my_matrix[0])\r\n sum_list = []\r\n sum_list.extend([sum (lines) for lines in my_matrix]) \r\n for col in range(iSize):\r\n sum_list.append(sum(row[col] for row in my_matrix))\r\n result1 = 0\r\n for i in range(0,iSize):\r\n result1 +=my_matrix[i][i]\r\n sum_list.append(result1) \r\n result2 = 0\r\n for i in range(iSize-1,-1,-1):\r\n result2 +=my_matrix[i][i]\r\n sum_list.append(result2)\r\n if len(set(sum_list))>1:\r\n return False\r\n return True", "source_id": "129"}{"text": "### Instruction\nWrite a function to find the item with maximum frequency in a given list.\n\n### Response\nfrom collections import defaultdict\r\ndef max_occurrences(nums):\r\n dict = defaultdict(int)\r\n for i in nums:\r\n dict[i] += 1\r\n result = max(dict.items(), key=lambda x: x[1]) \r\n return result", "source_id": "130"}{"text": "### Instruction\nWrite a python function to reverse only the vowels of a given string.\n\n### Response\ndef reverse_vowels(str1):\r\n\tvowels = \"\"\r\n\tfor char in str1:\r\n\t\tif char in \"aeiouAEIOU\":\r\n\t\t\tvowels += char\r\n\tresult_string = \"\"\r\n\tfor char in str1:\r\n\t\tif char in \"aeiouAEIOU\":\r\n\t\t\tresult_string += vowels[-1]\r\n\t\t\tvowels = vowels[:-1]\r\n\t\telse:\r\n\t\t\tresult_string += char\r\n\treturn result_string", "source_id": "131"}{"text": "### Instruction\nWrite a function to convert tuple to a string.\n\n### Response\ndef tup_string(tup1):\r\n str = ''.join(tup1)\r\n return str", "source_id": "132"}{"text": "### Instruction\nWrite a function to calculate the sum of the negative numbers of a given list of numbers using lambda function.\n\n### Response\ndef sum_negativenum(nums):\r\n sum_negativenum = list(filter(lambda nums:nums<0,nums))\r\n return sum(sum_negativenum)", "source_id": "133"}{"text": "### Instruction\nWrite a python function to check whether the last element of given array is even or odd after performing an operation p times.\n\n### Response\ndef check_last (arr,n,p): \r\n _sum = 0\r\n for i in range(n): \r\n _sum = _sum + arr[i] \r\n if p == 1: \r\n if _sum % 2 == 0: \r\n return \"ODD\"\r\n else: \r\n return \"EVEN\"\r\n return \"EVEN\"\r\n ", "source_id": "134"}{"text": "### Instruction\nWrite a function to find the nth hexagonal number.\n\n### Response\ndef hexagonal_num(n): \r\n\treturn n*(2*n - 1) ", "source_id": "135"}{"text": "### Instruction\nWrite a function to calculate electricity bill.\n\n### Response\ndef cal_electbill(units):\r\n if(units < 50):\r\n amount = units * 2.60\r\n surcharge = 25\r\n elif(units <= 100):\r\n amount = 130 + ((units - 50) * 3.25)\r\n surcharge = 35\r\n elif(units <= 200):\r\n amount = 130 + 162.50 + ((units - 100) * 5.26)\r\n surcharge = 45\r\n else:\r\n amount = 130 + 162.50 + 526 + ((units - 200) * 8.45)\r\n surcharge = 75\r\n total = amount + surcharge\r\n return total", "source_id": "136"}{"text": "### Instruction\nWrite a function to find the ration of zeroes in an array of integers.\n\n### Response\nfrom array import array\r\ndef zero_count(nums):\r\n n = len(nums)\r\n n1 = 0\r\n for x in nums:\r\n if x == 0:\r\n n1 += 1\r\n else:\r\n None\r\n return round(n1/n,2)", "source_id": "137"}{"text": "### Instruction\nWrite a python function to check whether the given number can be represented as sum of non-zero powers of 2 or not.\n\n### Response\ndef is_Sum_Of_Powers_Of_Two(n): \r\n if (n % 2 == 1): \r\n return False\r\n else: \r\n return True", "source_id": "138"}{"text": "### Instruction\nWrite a function to find the circumference of a circle.\n\n### Response\ndef circle_circumference(r):\r\n perimeter=2*3.1415*r\r\n return perimeter", "source_id": "139"}{"text": "### Instruction\nWrite a function to extract elements that occur singly in the given tuple list.\n\n### Response\ndef extract_singly(test_list):\r\n res = []\r\n temp = set()\r\n for inner in test_list:\r\n for ele in inner:\r\n if not ele in temp:\r\n temp.add(ele)\r\n res.append(ele)\r\n return (res) ", "source_id": "140"}{"text": "### Instruction\nWrite a function to sort a list of elements using pancake sort.\n\n### Response\ndef pancake_sort(nums):\r\n arr_len = len(nums)\r\n while arr_len > 1:\r\n mi = nums.index(max(nums[0:arr_len]))\r\n nums = nums[mi::-1] + nums[mi+1:len(nums)]\r\n nums = nums[arr_len-1::-1] + nums[arr_len:len(nums)]\r\n arr_len -= 1\r\n return nums", "source_id": "141"}{"text": "### Instruction\nWrite a function to count the same pair in three given lists.\n\n### Response\ndef count_samepair(list1,list2,list3):\r\n result = sum(m == n == o for m, n, o in zip(list1,list2,list3))\r\n return result", "source_id": "142"}{"text": "### Instruction\nWrite a function to find number of lists present in the given tuple.\n\n### Response\ndef find_lists(Input): \r\n\tif isinstance(Input, list): \r\n\t\treturn 1\r\n\telse: \r\n\t\treturn len(Input) ", "source_id": "143"}{"text": "### Instruction\nWrite a python function to find the sum of absolute differences in all pairs of the given array.\n\n### Response\ndef sum_Pairs(arr,n): \r\n sum = 0\r\n for i in range(n - 1,-1,-1): \r\n sum += i*arr[i] - (n-1-i) * arr[i] \r\n return sum", "source_id": "144"}{"text": "### Instruction\nWrite a python function to find the maximum difference between any two elements in a given array.\n\n### Response\ndef max_Abs_Diff(arr,n): \r\n minEle = arr[0] \r\n maxEle = arr[0] \r\n for i in range(1, n): \r\n minEle = min(minEle,arr[i]) \r\n maxEle = max(maxEle,arr[i]) \r\n return (maxEle - minEle) ", "source_id": "145"}{"text": "### Instruction\nWrite a function to find the ascii value of total characters in a string.\n\n### Response\ndef ascii_value_string(str1):\r\n for i in range(len(str1)):\r\n return ord(str1[i])", "source_id": "146"}{"text": "### Instruction\nWrite a function to find the maximum total path sum in the given triangle.\n\n### Response\ndef max_path_sum(tri, m, n): \r\n\tfor i in range(m-1, -1, -1): \r\n\t\tfor j in range(i+1): \r\n\t\t\tif (tri[i+1][j] > tri[i+1][j+1]): \r\n\t\t\t\ttri[i][j] += tri[i+1][j] \r\n\t\t\telse: \r\n\t\t\t\ttri[i][j] += tri[i+1][j+1] \r\n\treturn tri[0][0]", "source_id": "147"}{"text": "### Instruction\nWrite a function to divide a number into two parts such that the sum of digits is maximum.\n\n### Response\ndef sum_digits_single(x) : \r\n ans = 0\r\n while x : \r\n ans += x % 10\r\n x //= 10 \r\n return ans \r\ndef closest(x) : \r\n ans = 0\r\n while (ans * 10 + 9 <= x) : \r\n ans = ans * 10 + 9 \r\n return ans \r\ndef sum_digits_twoparts(N) : \r\n A = closest(N) \r\n return sum_digits_single(A) + sum_digits_single(N - A) ", "source_id": "148"}{"text": "### Instruction\nWrite a function to find the longest subsequence such that the difference between adjacents is one for the given array.\n\n### Response\ndef longest_subseq_with_diff_one(arr, n): \r\n\tdp = [1 for i in range(n)] \r\n\tfor i in range(n): \r\n\t\tfor j in range(i): \r\n\t\t\tif ((arr[i] == arr[j]+1) or (arr[i] == arr[j]-1)): \r\n\t\t\t\tdp[i] = max(dp[i], dp[j]+1) \r\n\tresult = 1\r\n\tfor i in range(n): \r\n\t\tif (result < dp[i]): \r\n\t\t\tresult = dp[i] \r\n\treturn result", "source_id": "149"}{"text": "### Instruction\nWrite a python function to find whether the given number is present in the infinite sequence or not.\n\n### Response\ndef does_Contain_B(a,b,c): \r\n if (a == b): \r\n return True\r\n if ((b - a) * c > 0 and (b - a) % c == 0): \r\n return True\r\n return False", "source_id": "150"}{"text": "### Instruction\nWrite a python function to check whether the given number is co-prime or not.\n\n### Response\ndef gcd(p,q):\r\n while q != 0:\r\n p, q = q,p%q\r\n return p\r\ndef is_coprime(x,y):\r\n return gcd(x,y) == 1", "source_id": "151"}{"text": "### Instruction\nWrite a function to sort the given array by using merge sort.\n\n### Response\ndef merge(a,b):\r\n c = []\r\n while len(a) != 0 and len(b) != 0:\r\n if a[0] < b[0]:\r\n c.append(a[0])\r\n a.remove(a[0])\r\n else:\r\n c.append(b[0])\r\n b.remove(b[0])\r\n if len(a) == 0:\r\n c += b\r\n else:\r\n c += a\r\n return c\r\ndef merge_sort(x):\r\n if len(x) == 0 or len(x) == 1:\r\n return x\r\n else:\r\n middle = len(x)//2\r\n a = merge_sort(x[:middle])\r\n b = merge_sort(x[middle:])\r\n return merge(a,b)\r\n", "source_id": "152"}{"text": "### Instruction\nWrite a function to find the vertex of a parabola.\n\n### Response\ndef parabola_vertex(a, b, c): \r\n vertex=(((-b / (2 * a)),(((4 * a * c) - (b * b)) / (4 * a))))\r\n return vertex", "source_id": "153"}{"text": "### Instruction\nWrite a function to extract every specified element from a given two dimensional list.\n\n### Response\ndef specified_element(nums, N):\r\n result = [i[N] for i in nums]\r\n return result", "source_id": "154"}{"text": "### Instruction\nWrite a python function to toggle all even bits of a given number.\n\n### Response\ndef even_bit_toggle_number(n) : \r\n res = 0; count = 0; temp = n \r\n while (temp > 0) : \r\n if (count % 2 == 1) : \r\n res = res | (1 << count) \r\n count = count + 1\r\n temp >>= 1 \r\n return n ^ res ", "source_id": "155"}{"text": "### Instruction\nWrite a function to convert a tuple of string values to a tuple of integer values.\n\n### Response\ndef tuple_int_str(tuple_str):\r\n result = tuple((int(x[0]), int(x[1])) for x in tuple_str)\r\n return result", "source_id": "156"}{"text": "### Instruction\nWrite a function to reflect the run-length encoding from a list.\n\n### Response\nfrom itertools import groupby\r\ndef encode_list(list1):\r\n return [[len(list(group)), key] for key, group in groupby(list1)]", "source_id": "157"}{"text": "### Instruction\nWrite a python function to find k number of operations required to make all elements equal.\n\n### Response\ndef min_Ops(arr,n,k): \r\n max1 = max(arr) \r\n res = 0\r\n for i in range(0,n): \r\n if ((max1 - arr[i]) % k != 0): \r\n return -1 \r\n else: \r\n res += (max1 - arr[i]) / k \r\n return int(res) ", "source_id": "158"}{"text": "### Instruction\nWrite a function to print the season for the given month and day.\n\n### Response\ndef month_season(month,days):\r\n if month in ('January', 'February', 'March'):\r\n\t season = 'winter'\r\n elif month in ('April', 'May', 'June'):\r\n\t season = 'spring'\r\n elif month in ('July', 'August', 'September'):\r\n\t season = 'summer'\r\n else:\r\n\t season = 'autumn'\r\n if (month == 'March') and (days > 19):\r\n\t season = 'spring'\r\n elif (month == 'June') and (days > 20):\r\n\t season = 'summer'\r\n elif (month == 'September') and (days > 21):\r\n\t season = 'autumn'\r\n elif (month == 'October') and (days > 21):\r\n\t season = 'autumn'\r\n elif (month == 'November') and (days > 21):\r\n\t season = 'autumn'\r\n elif (month == 'December') and (days > 20):\r\n\t season = 'winter'\r\n return season", "source_id": "159"}{"text": "### Instruction\nWrite a function to find x and y that satisfies ax + by = n.\n\n### Response\ndef solution (a, b, n): \r\n\ti = 0\r\n\twhile i * a <= n: \r\n\t\tif (n - (i * a)) % b == 0: \r\n\t\t\treturn (\"x = \",i ,\", y = \", \r\n\t\t\tint((n - (i * a)) / b)) \r\n\t\t\treturn 0\r\n\t\ti = i + 1\r\n\treturn (\"No solution\") ", "source_id": "160"}{"text": "### Instruction\nWrite a function to remove all elements from a given list present in another list.\n\n### Response\ndef remove_elements(list1, list2):\r\n result = [x for x in list1 if x not in list2]\r\n return result", "source_id": "161"}{"text": "### Instruction\nWrite a function to calculate the sum of the positive integers of n+(n-2)+(n-4)... (until n-x =< 0).\n\n### Response\ndef sum_series(n):\r\n if n < 1:\r\n return 0\r\n else:\r\n return n + sum_series(n - 2)", "source_id": "162"}{"text": "### Instruction\nWrite a function to calculate the area of a regular polygon.\n\n### Response\nfrom math import tan, pi\r\ndef area_polygon(s,l):\r\n area = s * (l ** 2) / (4 * tan(pi / s))\r\n return area", "source_id": "163"}{"text": "### Instruction\nWrite a python function to check whether the sum of divisors are same or not.\n\n### Response\nimport math \r\ndef divSum(n): \r\n sum = 1; \r\n i = 2; \r\n while(i * i <= n): \r\n if (n % i == 0): \r\n sum = (sum + i +math.floor(n / i)); \r\n i += 1; \r\n return sum; \r\ndef areEquivalent(num1,num2): \r\n return divSum(num1) == divSum(num2); ", "source_id": "164"}{"text": "### Instruction\nWrite a python function to count characters at same position in a given string (lower and uppercase characters) as in english alphabet.\n\n### Response\ndef count_char_position(str1): \r\n count_chars = 0\r\n for i in range(len(str1)):\r\n if ((i == ord(str1[i]) - ord('A')) or \r\n (i == ord(str1[i]) - ord('a'))): \r\n count_chars += 1\r\n return count_chars ", "source_id": "165"}{"text": "### Instruction\nWrite a python function to count the pairs with xor as an even number.\n\n### Response\ndef find_even_Pair(A,N): \r\n evenPair = 0\r\n for i in range(0,N): \r\n for j in range(i+1,N): \r\n if ((A[i] ^ A[j]) % 2 == 0): \r\n evenPair+=1\r\n return evenPair; ", "source_id": "166"}{"text": "### Instruction\nWrite a python function to find smallest power of 2 greater than or equal to n.\n\n### Response\ndef next_Power_Of_2(n): \r\n count = 0; \r\n if (n and not(n & (n - 1))): \r\n return n \r\n while( n != 0): \r\n n >>= 1\r\n count += 1\r\n return 1 << count; ", "source_id": "167"}{"text": "### Instruction\nWrite a python function to find the frequency of a number in a given array.\n\n### Response\ndef frequency(a,x): \r\n count = 0 \r\n for i in a: \r\n if i == x: count += 1\r\n return count ", "source_id": "168"}{"text": "### Instruction\nWrite a function to calculate the nth pell number.\n\n### Response\ndef get_pell(n): \r\n\tif (n <= 2): \r\n\t\treturn n \r\n\ta = 1\r\n\tb = 2\r\n\tfor i in range(3, n+1): \r\n\t\tc = 2 * b + a \r\n\t\ta = b \r\n\t\tb = c \r\n\treturn b ", "source_id": "169"}{"text": "### Instruction\nWrite a function to find sum of the numbers in a list between the indices of a specified range.\n\n### Response\ndef sum_range_list(list1, m, n): \r\n sum_range = 0 \r\n for i in range(m, n+1, 1): \r\n sum_range += list1[i] \r\n return sum_range ", "source_id": "170"}{"text": "### Instruction\nWrite a function to find the perimeter of a pentagon.\n\n### Response\nimport math\r\ndef perimeter_pentagon(a):\r\n perimeter=(5*a)\r\n return perimeter", "source_id": "171"}{"text": "### Instruction\nWrite a function to find the occurence of characters 'std' in the given string 1. list item 1. list item 1. list item 2. list item 2. list item 2. list item\n\n### Response\ndef count_occurance(s):\r\n count=0\r\n for i in range(len(s)):\r\n if (s[i]== 's' and s[i+1]=='t' and s[i+2]== 'd'):\r\n count = count + 1\r\n return count", "source_id": "172"}{"text": "### Instruction\nWrite a function to remove everything except alphanumeric characters from a string.\n\n### Response\nimport re\r\ndef remove_splchar(text): \r\n pattern = re.compile('[\\W_]+')\r\n return (pattern.sub('', text))", "source_id": "173"}{"text": "### Instruction\nWrite a function to group a sequence of key-value pairs into a dictionary of lists.\n\n### Response\ndef group_keyvalue(l):\r\n result = {}\r\n for k, v in l:\r\n result.setdefault(k, []).append(v)\r\n return result", "source_id": "174"}{"text": "### Instruction\nWrite a function to verify validity of a string of parentheses.\n\n### Response\ndef is_valid_parenthese( str1):\r\n stack, pchar = [], {\"(\": \")\", \"{\": \"}\", \"[\": \"]\"}\r\n for parenthese in str1:\r\n if parenthese in pchar:\r\n stack.append(parenthese)\r\n elif len(stack) == 0 or pchar[stack.pop()] != parenthese:\r\n return False\r\n return len(stack) == 0", "source_id": "175"}{"text": "### Instruction\nWrite a function to find the perimeter of a triangle.\n\n### Response\ndef perimeter_triangle(a,b,c):\r\n perimeter=a+b+c\r\n return perimeter", "source_id": "176"}{"text": "### Instruction\nWrite a python function to find two distinct numbers such that their lcm lies within the given range.\n\n### Response\ndef answer(L,R): \r\n if (2 * L <= R): \r\n return (L ,2*L)\r\n else: \r\n return (-1) ", "source_id": "177"}{"text": "### Instruction\nWrite a function to search some literals strings in a string.\n\n### Response\nimport re\r\ndef string_literals(patterns,text):\r\n for pattern in patterns:\r\n if re.search(pattern, text):\r\n return ('Matched!')\r\n else:\r\n return ('Not Matched!')", "source_id": "178"}{"text": "### Instruction\nWrite a function to find if the given number is a keith number or not.\n\n### Response\ndef is_num_keith(x): \r\n\tterms = [] \r\n\ttemp = x \r\n\tn = 0 \r\n\twhile (temp > 0): \r\n\t\tterms.append(temp % 10) \r\n\t\ttemp = int(temp / 10) \r\n\t\tn+=1 \r\n\tterms.reverse() \r\n\tnext_term = 0 \r\n\ti = n \r\n\twhile (next_term < x): \r\n\t\tnext_term = 0 \r\n\t\tfor j in range(1,n+1): \r\n\t\t\tnext_term += terms[i - j] \r\n\t\tterms.append(next_term) \r\n\t\ti+=1 \r\n\treturn (next_term == x) ", "source_id": "179"}{"text": "### Instruction\nWrite a function to calculate distance between two points using latitude and longitude.\n\n### Response\nfrom math import radians, sin, cos, acos\r\ndef distance_lat_long(slat,slon,elat,elon):\r\n dist = 6371.01 * acos(sin(slat)*sin(elat) + cos(slat)*cos(elat)*cos(slon - elon))\r\n return dist", "source_id": "180"}{"text": "### Instruction\nWrite a function to find the longest common prefix in the given set of strings.\n\n### Response\ndef common_prefix_util(str1, str2): \r\n\tresult = \"\"; \r\n\tn1 = len(str1) \r\n\tn2 = len(str2) \r\n\ti = 0\r\n\tj = 0\r\n\twhile i <= n1 - 1 and j <= n2 - 1: \r\n\t\tif (str1[i] != str2[j]): \r\n\t\t\tbreak\r\n\t\tresult += str1[i] \r\n\t\ti += 1\r\n\t\tj += 1\r\n\treturn (result) \r\ndef common_prefix (arr, n): \r\n\tprefix = arr[0] \r\n\tfor i in range (1, n): \r\n\t\tprefix = common_prefix_util(prefix, arr[i]) \r\n\treturn (prefix) ", "source_id": "181"}{"text": "### Instruction\nWrite a function to find uppercase, lowercase, special character and numeric values using regex.\n\n### Response\nimport re\r\ndef find_character(string):\r\n uppercase_characters = re.findall(r\"[A-Z]\", string) \r\n lowercase_characters = re.findall(r\"[a-z]\", string) \r\n numerical_characters = re.findall(r\"[0-9]\", string) \r\n special_characters = re.findall(r\"[, .!?]\", string) \r\n return uppercase_characters, lowercase_characters, numerical_characters, special_characters", "source_id": "182"}{"text": "### Instruction\nWrite a function to count all the distinct pairs having a difference of k in any array.\n\n### Response\ndef count_pairs(arr, n, k):\r\n count=0;\r\n for i in range(0,n):\r\n for j in range(i+1, n):\r\n if arr[i] - arr[j] == k or arr[j] - arr[i] == k:\r\n count += 1\r\n return count", "source_id": "183"}{"text": "### Instruction\nWrite a function to find all the values in a list that are greater than a specified number.\n\n### Response\ndef greater_specificnum(list,num):\r\n greater_specificnum=all(x >= num for x in list)\r\n return greater_specificnum", "source_id": "184"}{"text": "### Instruction\nWrite a function to find the focus of a parabola.\n\n### Response\ndef parabola_focus(a, b, c): \r\n focus= (((-b / (2 * a)),(((4 * a * c) - (b * b) + 1) / (4 * a))))\r\n return focus", "source_id": "185"}{"text": "### Instruction\nWrite a function to search some literals strings in a string by using regex.\n\n### Response\nimport re\r\ndef check_literals(text, patterns):\r\n for pattern in patterns:\r\n if re.search(pattern, text):\r\n return ('Matched!')\r\n else:\r\n return ('Not Matched!')", "source_id": "186"}{"text": "### Instruction\nWrite a function to find the longest common subsequence for the given two sequences.\n\n### Response\ndef longest_common_subsequence(X, Y, m, n): \r\n if m == 0 or n == 0: \r\n return 0 \r\n elif X[m-1] == Y[n-1]: \r\n return 1 + longest_common_subsequence(X, Y, m-1, n-1) \r\n else: \r\n return max(longest_common_subsequence(X, Y, m, n-1), longest_common_subsequence(X, Y, m-1, n))", "source_id": "187"}{"text": "### Instruction\nWrite a python function to check whether the given number can be represented by product of two squares or not.\n\n### Response\ndef prod_Square(n):\r\n for i in range(2,(n) + 1):\r\n if (i*i < (n+1)):\r\n for j in range(2,n + 1):\r\n if ((i*i*j*j) == n):\r\n return True;\r\n return False;", "source_id": "188"}{"text": "### Instruction\nWrite a python function to find the first missing positive number.\n\n### Response\ndef first_Missing_Positive(arr,n): \r\n ptr = 0\r\n for i in range(n):\r\n if arr[i] == 1:\r\n ptr = 1\r\n break\r\n if ptr == 0:\r\n return(1)\r\n for i in range(n):\r\n if arr[i] <= 0 or arr[i] > n:\r\n arr[i] = 1\r\n for i in range(n):\r\n arr[(arr[i] - 1) % n] += n\r\n for i in range(n):\r\n if arr[i] <= n:\r\n return(i + 1)\r\n return(n + 1)", "source_id": "189"}{"text": "### Instruction\nWrite a python function to count the number of integral co-ordinates that lie inside a square.\n\n### Response\ndef count_Intgral_Points(x1,y1,x2,y2): \r\n return ((y2 - y1 - 1) * (x2 - x1 - 1)) ", "source_id": "190"}{"text": "### Instruction\nWrite a function to check whether the given month name contains 30 days or not.\n\n### Response\ndef check_monthnumber(monthname3):\r\n if monthname3 ==\"April\" or monthname3== \"June\" or monthname3== \"September\" or monthname3== \"November\":\r\n return True\r\n else:\r\n return False", "source_id": "191"}{"text": "### Instruction\nWrite a python function to check whether a string has atleast one letter and one number.\n\n### Response\ndef check_String(str): \r\n flag_l = False\r\n flag_n = False\r\n for i in str: \r\n if i.isalpha(): \r\n flag_l = True \r\n if i.isdigit(): \r\n flag_n = True\r\n return flag_l and flag_n ", "source_id": "192"}{"text": "### Instruction\nWrite a function to remove the duplicates from the given tuple.\n\n### Response\ndef remove_tuple(test_tup):\r\n res = tuple(set(test_tup))\r\n return (res) ", "source_id": "193"}{"text": "### Instruction\nWrite a python function to convert octal number to decimal number.\n\n### Response\ndef octal_To_Decimal(n): \r\n num = n; \r\n dec_value = 0; \r\n base = 1; \r\n temp = num; \r\n while (temp): \r\n last_digit = temp % 10; \r\n temp = int(temp / 10); \r\n dec_value += last_digit*base; \r\n base = base * 8; \r\n return dec_value; ", "source_id": "194"}{"text": "### Instruction\nWrite a python function to find the first position of an element in a sorted array.\n\n### Response\ndef first(arr,x,n): \r\n low = 0\r\n high = n - 1\r\n res = -1 \r\n while (low <= high):\r\n mid = (low + high) // 2 \r\n if arr[mid] > x:\r\n high = mid - 1\r\n elif arr[mid] < x:\r\n low = mid + 1\r\n else:\r\n res = mid\r\n high = mid - 1\r\n return res", "source_id": "195"}{"text": "### Instruction\nWrite a function to remove all the tuples with length k.\n\n### Response\ndef remove_tuples(test_list, K):\r\n res = [ele for ele in test_list if len(ele) != K]\r\n return (res) ", "source_id": "196"}{"text": "### Instruction\nWrite a function to perform the exponentiation of the given two tuples.\n\n### Response\ndef find_exponentio(test_tup1, test_tup2):\r\n res = tuple(ele1 ** ele2 for ele1, ele2 in zip(test_tup1, test_tup2))\r\n return (res)\r\n", "source_id": "197"}{"text": "### Instruction\nWrite a function to find the largest triangle that can be inscribed in an ellipse.\n\n### Response\nimport math\r\ndef largest_triangle(a,b): \r\n if (a < 0 or b < 0): \r\n return -1 \r\n area = (3 * math.sqrt(3) * pow(a, 2)) / (4 * b); \r\n return area ", "source_id": "198"}{"text": "### Instruction\nWrite a python function to find highest power of 2 less than or equal to given number.\n\n### Response\ndef highest_Power_of_2(n): \r\n res = 0; \r\n for i in range(n, 0, -1): \r\n if ((i & (i - 1)) == 0): \r\n res = i; \r\n break; \r\n return res; ", "source_id": "199"}{"text": "### Instruction\nWrite a function to find all index positions of the maximum values in a given list.\n\n### Response\ndef position_max(list1):\r\n max_val = max(list1)\r\n max_result = [i for i, j in enumerate(list1) if j == max_val]\r\n return max_result", "source_id": "200"}{"text": "### Instruction\nWrite a python function to check whether the elements in a list are same or not.\n\n### Response\ndef chkList(lst): \r\n return len(set(lst)) == 1", "source_id": "201"}{"text": "### Instruction\nWrite a function to remove even characters in a string.\n\n### Response\ndef remove_even(str1):\r\n str2 = ''\r\n for i in range(1, len(str1) + 1):\r\n if(i % 2 != 0):\r\n str2 = str2 + str1[i - 1]\r\n return str2", "source_id": "202"}{"text": "### Instruction\nWrite a python function to find the hamming distance between given two integers.\n\n### Response\ndef hamming_Distance(n1,n2) : \r\n x = n1 ^ n2 \r\n setBits = 0\r\n while (x > 0) : \r\n setBits += x & 1\r\n x >>= 1\r\n return setBits ", "source_id": "203"}{"text": "### Instruction\nWrite a python function to count the occurrence of a given character in a string.\n\n### Response\ndef count(s,c) : \r\n res = 0 \r\n for i in range(len(s)) : \r\n if (s[i] == c): \r\n res = res + 1\r\n return res ", "source_id": "204"}{"text": "### Instruction\nWrite a function to find the inversions of tuple elements in the given tuple list.\n\n### Response\ndef inversion_elements(test_tup):\r\n res = tuple(list(map(lambda x: ~x, list(test_tup))))\r\n return (res) ", "source_id": "205"}{"text": "### Instruction\nWrite a function to perform the adjacent element concatenation in the given tuples.\n\n### Response\ndef concatenate_elements(test_tup):\r\n res = tuple(i + j for i, j in zip(test_tup, test_tup[1:]))\r\n return (res) ", "source_id": "206"}{"text": "### Instruction\nWrite a function to count the longest repeating subsequences such that the two subsequences don’t have same string characters at same positions.\n\n### Response\ndef find_longest_repeating_subseq(str): \r\n\tn = len(str) \r\n\tdp = [[0 for k in range(n+1)] for l in range(n+1)] \r\n\tfor i in range(1, n+1): \r\n\t\tfor j in range(1, n+1): \r\n\t\t\tif (str[i-1] == str[j-1] and i != j): \r\n\t\t\t\tdp[i][j] = 1 + dp[i-1][j-1] \r\n\t\t\telse: \r\n\t\t\t\tdp[i][j] = max(dp[i][j-1], dp[i-1][j]) \r\n\treturn dp[n][n]", "source_id": "207"}{"text": "### Instruction\nWrite a function to check the given decimal with a precision of 2 by using regex.\n\n### Response\nimport re\r\ndef is_decimal(num):\r\n num_fetch = re.compile(r\"\"\"^[0-9]+(\\.[0-9]{1,2})?$\"\"\")\r\n result = num_fetch.search(num)\r\n return bool(result)", "source_id": "208"}{"text": "### Instruction\nWrite a function to delete the smallest element from the given heap and then insert a new item.\n\n### Response\nimport heapq as hq\r\ndef heap_replace(heap,a):\r\n hq.heapify(heap)\r\n hq.heapreplace(heap, a)\r\n return heap", "source_id": "209"}{"text": "### Instruction\nWrite a function to check that the given string contains only a certain set of characters(in this case a-z, a-z and 0-9) by using regex.\n\n### Response\nimport re\r\ndef is_allowed_specific_char(string):\r\n get_char = re.compile(r'[^a-zA-Z0-9.]')\r\n string = get_char.search(string)\r\n return not bool(string)", "source_id": "210"}123456789101112131415161718{ "id": "cortex-code-tests", "source": "google-research-datasets/mbpp", "config": "full", "split": "test", "origin": "Hugging Face Hub dataset repository google-research-datasets/mbpp", "license": "cc-by-4.0", "license_url": "https://huggingface.co/datasets/google-research-datasets/mbpp", "redistribution": "yes", "attribution": "MBPP (Mostly Basic Python Problems), Google Research, distributed under CC BY 4.0.", "record_type": "code-sft", "rows_fetched": 200, "records_written": 200, "jsonl_sha256": "eca5b5ade32869b07e216a93a81d0c5355fd09ffb4224ac37184e502e934dd34", "jsonl_bytes": 69806, "note": "Python problem statements with reference solutions. Suitable for evaluation and instruction tuning.", "fetched_via": "https://datasets-server.huggingface.co/rows"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697{ "_comment": [ "Declared sources for CORTEX training data.", "Every dataset must state its origin and license. training/train.py refuses to run on", "a dataset that is not declared here or whose license is unknown, absent or proprietary.", "Licenses below were read from the Hugging Face Hub API, not from memory." ], "schema_version": 1, "datasets": [ { "id": "cortex-code-sft", "source": "sahil2801/CodeAlpaca-20k", "config": "default", "split": "train", "origin": "Hugging Face Hub dataset repository sahil2801/CodeAlpaca-20k", "license": "cc-by-4.0", "license_url": "https://huggingface.co/datasets/sahil2801/CodeAlpaca-20k", "redistribution": "yes", "attribution": "CodeAlpaca-20k, distributed under CC BY 4.0. Attribution required: cite the dataset repository above when redistributing.", "record_type": "code-sft", "fields": { "prompt": "instruction", "completion": "output", "instruction_field": "instruction", "input_field": "input" }, "id_field": null, "path": "datasets/cortex-code-sft.jsonl", "note": "Instruction/response pairs for code generation. CC BY 4.0 permits redistribution and commercial use with attribution." }, { "id": "cortex-code-tests", "source": "google-research-datasets/mbpp", "config": "full", "split": "test", "origin": "Hugging Face Hub dataset repository google-research-datasets/mbpp", "license": "cc-by-4.0", "license_url": "https://huggingface.co/datasets/google-research-datasets/mbpp", "redistribution": "yes", "attribution": "MBPP (Mostly Basic Python Problems), Google Research, distributed under CC BY 4.0.", "record_type": "code-sft", "fields": { "prompt": "text", "completion": "code" }, "id_field": "task_id", "path": "datasets/cortex-code-tests.jsonl", "note": "Python problem statements with reference solutions. Suitable for evaluation and instruction tuning." }, { "id": "cortex-code-eval", "source": "openai/openai_humaneval", "config": "openai_humaneval", "split": "test", "origin": "Hugging Face Hub dataset repository openai/openai_humaneval", "license": "mit", "license_url": "https://huggingface.co/datasets/openai/openai_humaneval", "redistribution": "yes", "attribution": "HumanEval, OpenAI, distributed under the MIT license.", "record_type": "code-sft", "fields": { "prompt": "prompt", "completion": "canonical_solution" }, "id_field": "task_id", "path": "datasets/cortex-code-eval.jsonl", "note": "Held out for evaluation only. Must not be trained on: doing so would invalidate the evaluation." } ], "rejected": [ { "source": "bigcode/the-stack-dedup", "license": "other", "reason": "License field is 'other' with gated access; the governing terms are not verifiable from the Hub metadata alone." }, { "source": "bigcode/starcoderdata", "license": "other", "reason": "License field is 'other' and access is gated; per-file source licenses are not declared at dataset level." }, { "source": "codeparrot/codeparrot-clean", "license": null, "reason": "No license declared on the Hub. Cannot be redistributed or used without an explicit grant." }, { "source": "codeparrot/github-code", "license": "other", "reason": "License field is 'other'; terms are not verifiable from Hub metadata alone." }, { "source": "iamtarun/python_code_instructions_18k_alpaca", "license": null, "reason": "No license declared on the Hub." } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272# Audit technique du modèle distribué
Ce document décrit **ce qui est réellement présent** dans le dépôt `Frankenstein-Labs/Cortex-ai`au commit `e1985ae`, tel que mesuré depuis les en-têtes SafeTensors des 66 shards et depuis lesfichiers de configuration. Aucune valeur n'est reprise de mémoire ni d'une source tierce.
Règle de lecture : tout ce qui suit est **mesuré**. Ce qui n'a pas été mesuré est signalé comme tel.
---
## 1. Résumé
| Élément | Valeur mesurée ||---|---|| Paramètres logiques | **1 650 497 936 906** (1,65 T) || Octets stockés | **892 727 580 904** (892,73 Go) || Tenseurs | **149 782** || Shards | **66** + 1 index || Architecture | `DeepseekV4ForCausalLM`, `model_type: deepseek_v4` || Type déclaré | `bfloat16` || Quantification | FP8 `e4m3` (poids denses) + FP4 (experts routés) || Contexte maximal | 1 048 576 tokens || Vocabulaire | 129 280 || Licence | MIT — Copyright (c) 2023 DeepSeek |
Les paramètres logiques et les octets stockés **réconcilient exactement** avec les métadonnées del'index (`total_size: 892727580904`, écart = 0 octet) et avec le champ `safetensors` du Hub(1 650 497 936 906). Les 149 782 noms de tenseurs des 66 en-têtes correspondent un à un à ceux del'index, sans nom manquant ni ajouté.
---
## 2. Dimensions d'architecture (depuis `config.json`)
| Champ | Valeur ||---|---|| `hidden_size` | 7 168 || `num_hidden_layers` | 61 || `num_nextn_predict_layers` | 1 || `num_hash_layers` | 3 || `num_attention_heads` | 128 || `num_key_value_heads` | 1 || `head_dim` | 512 || `qk_rope_head_dim` | 64 || `q_lora_rank` | 1 536 || `o_lora_rank` | 1 024 || `o_groups` | 16 || `moe_intermediate_size` | 3 072 || `n_routed_experts` | 384 || `n_shared_experts` | 1 || `num_experts_per_tok` | 6 || `vocab_size` | 129 280 || `max_position_embeddings` | 1 048 576 || `rope_theta` | 10 000 || `rope_scaling` | yarn, facteur 16, base 65 536 || `compress_rope_theta` | 160 000 || `rms_norm_eps` | 1e-06 || `hidden_act` | silu || `scoring_func` | sqrtsoftplus || `topk_method` | noaux_tc || `routed_scaling_factor` | 2.5 || `swiglu_limit` | 10.0 || `sliding_window` | 128 || `tie_word_embeddings` | **false** || `expert_dtype` | fp4 || `attention_dropout` | 0.0 |
### Champs présents mais non matérialisés dans les poids
| Champ | Valeur | Observation mesurée ||---|---|---|| `index_head_dim` | 128 | cohérent avec `indexer` (voir §4) || `index_n_heads` | 64 | cohérent avec `weights_proj` `[64, 7168]` || `index_topk` | 1 024 | paramètre de calcul, sans tenseur || `num_hash_layers` | 3 | les couches 0–2 portent `ffn.gate.tid2eid` || `hc_mult`, `hc_eps`, `hc_sinkhorn_iters` | 4 / 1e-6 / 20 | pas de tenseur dédié || `dspark_*` (4 champs) | — | **aucun tenseur `dspark` n'existe** || `compress_ratios` (64 valeurs) | 60×128, 4×4, 3×0 | 61 couches + 3 MTP |
Le champ `compress_ratios` compte 64 entrées pour 61 couches + 3 têtes MTP ; les trois `0`finaux correspondent aux couches MTP, qui n'ont pas de `compressor` (confirmé au §4).
---
## 3. Structure des shards
| Propriété | Valeur ||---|---|| Shards | 66, nommés `model-00001-of-00066.safetensors` … `model-00066-of-00066.safetensors` || Index | `model.safetensors.index.json`, `total_size = 892 727 580 904` || Tenseurs indexés | 149 782 || Tenseurs par shard | de 1 (shard 1 : `embed.weight`) à 2 344 || Empreinte | SHA-256 identique au dépôt d'origine, 67/67 objets LFS |
Le shard 1 ne contient qu'un seul tenseur : `embed.weight`, `BF16 [129280, 7168]`, soit 1,85 Go.
### Types de stockage observés
| dtype SafeTensors | Nombre de tenseurs | Rôle ||---|---|---|| `F8_E8M0` | 74 271 | échelles de quantification par blocs || `I8` | 73 728 | poids d'experts, **2 valeurs FP4 par octet** || `BF16` | 631 | embeddings, normes, gates, compresseurs || `F32` | 606 | sinks d'attention, `ape`, tenseurs `hc_*` || `F8_E4M3` | 543 | poids denses FP8 (attention, experts partagés) || `I64` | 3 | `ffn.gate.tid2eid` |
Les experts sont donc stockés en **FP4 réel** (packing 2/octet), pas en FP8 : c'est ce quedécrivent `expert_dtype: fp4` et `quantization_config.fmt: e4m3`.
---
## 4. Anatomie d'une couche de décodeur
61 couches, indices 0 à 60. Deux familles :
| Famille | Indices | Particularité ||---|---|---|| Couches « hash » | 0, 1, 2 | `ffn.gate.tid2eid` (routage par table token→expert) || Couches « apprises » | 3 … 60 | `ffn.gate.bias` (biais de routage) || Couches avec `indexer` | paires 2, 4, 6, … 60 | 30 couches sur 61 |
### Composants présents dans **toutes** les couches
| Tenseur | dtype | Forme mesurée | Interprétation ||---|---|---|---|| `attn.wq_a.weight` | `F8_E4M3` | `[1536, 7168]` | projection Q, descente `q_lora_rank` || `attn.wq_b.weight` | `F8_E4M3` | `[65536, 1536]` | projection Q, remontée (128 têtes × 512) || `attn.wkv.weight` | `F8_E4M3` | `[512, 7168]` | projection KV, 1 tête || `attn.wo_a.weight` | `F8_E4M3` | `[16384, 4096]` | sortie groupée, 16 groupes × 1024 || `attn.wo_b.weight` | `F8_E4M3` | `[7168, 16384]` | remontée de sortie || `attn.q_norm.weight` | `BF16` | `[1536]` | norme Q (rang LoRA) || `attn.kv_norm.weight` | `BF16` | `[512]` | norme KV (head_dim) || `attn.attn_sink` | `F32` | `[128]` | sink par tête d'attention || `attn.compressor.wkv.weight` | `BF16` | `[512, 7168]` | compresseur de contexte || `attn.compressor.wgate.weight` | `BF16` | `[512, 7168]` | porte du compresseur || `attn.compressor.ape` | `F32` | `[128, 512]` | embeddings positionnels du compresseur || `attn.compressor.norm.weight` | `BF16` | `[512]` | norme du compresseur || `attn_norm.weight` | `BF16` | `[7168]` | norme pré-attention || `ffn_norm.weight` | `BF16` | `[7168]` | norme pré-FFN || `ffn.gate.weight` | `BF16` | `[384, 7168]` | routeur MoE || `ffn.experts.N.w1.weight` | `I8` | `[3072, 3584]` | expert, porte, FP4 || `ffn.experts.N.w2.weight` | `I8` | `[7168, 1536]` | expert, descente, FP4 || `ffn.experts.N.w3.weight` | `I8` | `[3072, 3584]` | expert, montée, FP4 || `ffn.experts.N.w{1,2,3}.scale` | `F8_E8M0` | `[3072, 224]` etc. | échelles de blocs || `ffn.shared_experts.w1/w2/w3.weight` | `F8_E4M3` | `[3072, 7168]`, `[7168, 3072]`, `[3072, 7168]` | expert partagé || `hc_attn_base` | `F32` | `[24]` | tête de contrôle hyper-connectée || `hc_attn_scale` | `F32` | `[3]` | idem || `hc_attn_fn` | `F32` | `[24, 28672]` | idem, `hc_mult × hidden_size` || `hc_ffn_base` / `hc_ffn_scale` / `hc_ffn_fn` | `F32` | `[24]` / `[3]` / `[24, 28672]` | idem |
> **Attention aux formes des experts.** Les poids d'experts sont stockés en FP4, donc **deux valeurs> par octet** : la seconde dimension des tenseurs `I8` vaut la moitié de la dimension logique. Un> expert a donc les dimensions logiques `w1: [3072, 7168]`, `w2: [7168, 3072]`, `w3: [3072, 7168]`> — une FFN SwiGLU standard, avec `moe_intermediate_size = 3072`. Les échelles suivent le même> schéma : `[3072, 224]` pour 3584 colonnes stockées découpées en blocs de 128 avec une marge> d'alignement. Toute réimplémentation doit dépaqueter avant le produit matriciel.
### Composants spécifiques aux couches à `indexer` (30 couches)
| Tenseur | dtype | Forme mesurée ||---|---|---|| `attn.indexer.wq_b.weight` | `F8_E4M3` | `[8192, 1536]` || `attn.indexer.weights_proj.weight` | `BF16` | `[64, 7168]` || `attn.indexer.compressor.wkv.weight` | `BF16` | `[256, 7168]` || `attn.indexer.compressor.wgate.weight` | `BF16` | `[256, 7168]` || `attn.indexer.compressor.ape` | `F32` | `[4, 256]` || `attn.indexer.compressor.norm.weight` | `BF16` | `[128]` |
`weights_proj` `[64, 7168]` et `norm` `[128]` correspondent à `index_n_heads: 64` et`index_head_dim: 128`.
### Routage des experts
| Tenseur | dtype | Forme | Où ||---|---|---|---|| `ffn.gate.tid2eid` | `I64` | `[129280, 6]` | couches 0–2 || `ffn.gate.bias` | `F32` | `[384]` | couches 3–60 |
`tid2eid` associe chaque token du vocabulaire à 6 identifiants d'experts : le routage des troispremières couches est **déterministe par token**, sans tenseur appris.
---
## 5. Têtes MTP (multi-token prediction)
Trois têtes `mtp.0`, `mtp.1`, `mtp.2`. Chacune réplique une couche complète (attention + MoE +`hc_*`) et ajoute :
| Tenseur | dtype | Forme | Rôle ||---|---|---|---|| `main_proj.weight` | `F8_E4M3` | `[7168, 21504]` | projection de l'état principal || `main_norm.weight` | `BF16` | `[7168]` | norme associée || `norm.weight` | `BF16` | `[7168]` | norme de la tête || `confidence_head.proj.weight` | `BF16` | `[64, 128]` | tête de confiance || `markov_head.markov_w1.weight` | `BF16` | `[129280, 512]` | tête markov (rank 512) || `markov_head.markov_w2.weight` | `BF16` | `[129280, 512]` | tête markov || `hc_head_base` / `hc_head_scale` / `hc_head_fn` | `F32` | `[4]` / `[1]` / `[4, 28672]` | contrôle hyper-connecté |
`main_proj` `[7168, 21504]` = `3 × 7168`, soit les trois têtes empilées. `markov_head` `[129280, 512]`correspond à `vocab_size` et `dspark_markov_rank: 512`.
**Point non résolu.** `confidence_head` et `markov_head` apparaissent sur les trois têtes MTP,alors que `config.json` ne les décrit que par des champs `dspark_*` dont `dspark_target_layer_ids`vaut `[58, 59, 60]` — trois **couches**, pas trois têtes. Aucun tenseur `dspark` n'existe. Lacorrespondance entre `dspark_target_layer_ids` et les têtes `mtp.0/1/2` n'est donc **pasdémontrée** ici. À vérifier avant toute réutilisation.
---
## 6. En-tête et embeddings
| Tenseur | dtype | Forme ||---|---|---|| `embed.weight` | `BF16` | `[129280, 7168]` || `head.weight` | `BF16` | `[129280, 7168]` || `norm.weight` | `BF16` | `[7168]` || `hc_head_base` / `hc_head_scale` / `hc_head_fn` | `F32` | `[4]` / `[1]` / `[4, 28672]` |
`tie_word_embeddings: false` est confirmé : `embed` et `head` sont deux tenseurs distincts de926 679 040 paramètres chacun. **Aucun partage** n'est possible entre l'entrée et la sortie.
---
## 7. Tokenizer
| Propriété | Valeur ||---|---|| Classe | `PreTrainedTokenizerFast` || Modèle | BPE || Taille du vocabulaire BPE | 128 000 || Fusions | 127 741 || Tokens ajoutés | 1 283 || Identifiants uniques | **129 280** || `model_max_length` | 1 048 576 || `legacy` | `true` || Pré-tokenizer | `Split` sur `\p{N}{1,3}`, puis split CJK || Post-processeur / décodeur | ByteLevel || Normalizer | séquence vide (aucune normalisation) |
Tokens spéciaux : `bos` = id 0, `eos` = id 1, `pad` = id 2. `unk_token` vaut `null` : il n'y a**pas** de token inconnu déclaré.
### Écart à signaler
Le tokenizer expose 128 000 entrées BPE **plus** 1 283 tokens ajoutés, soit 129 283 compteurs,alors que `vocab_size` vaut 129 280 dans `config.json` et que `embed.weight` / `head.weight` ont129 280 lignes.
L'explication mesurée : les identifiants 0, 1 et 2 apparaissent **à la fois** comme tokensspéciaux ajoutés et comme entrées BPE. Le décompte réel des identifiants uniques est donc129 280. Vérifié par test : `128 000 + 1 283 − 3 = 129 280`. Toute réutilisation doit comparerles identifiants uniques, jamais les compteurs bruts.
---
## 8. Ce que cet audit ne prouve pas
- **Aucun chargement de bout en bout** du checkpoint n'a été exécuté : l'environnement de développement dispose de 4 cœurs, ~15 Gio de RAM et aucun GPU, pour un modèle qui exige au minimum ~1,65 To de mémoire d'inférence.- Les formes et types proviennent des **en-têtes SafeTensors**, pas de tenseurs chargés.- Aucune performance, aucune qualité de génération et aucun résultat de benchmark n'a été mesuré.- La sémantique exacte des tenseurs `hc_*` (hyper-connections), du `compressor` et des têtes MTP n'est pas documentée dans le dépôt : les interprétations ci-dessus sont déduites des formes et des noms, et sont signalées comme telles.- La correspondance `dspark_*` ↔ têtes MTP reste non démontrée (§5).
---
*Audit produit sur le commit `e1985ae`, à partir des 66 en-têtes de shards, de`model.safetensors.index.json`, de `config.json`, `generation_config.json` et `tokenizer_config.json`.*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# Pipeline CORTEX
Ce dossier contient le pipeline qui produit les **propres poids CORTEX** deFrankenstein-Labs : définition du modèle, tokenizer, entraînement, datasets,checkpoints et évaluation.
## Règle de provenance
Ce pipeline est **strictement séparé** du checkpoint de 1,65 T distribué dans ce dépôt.
| | Checkpoint distribué | Poids produits par ce pipeline ||---|---|---|| Origine | `deepseek-ai/DeepSeek-V4-Pro-0813` | Frankenstein-Labs || Entraînement | DeepSeek-AI | Frankenstein-Labs || Fichiers | `model-0000*.safetensors` | `checkpoints/**` || Licence | MIT (Copyright 2023 DeepSeek) | MIT || Modifié par ce pipeline | **non** | — |
Aucun script de ce dossier ne lit, ne modifie ni ne remplace les 66 shards distribués.`base_model` ne sera renseigné pour un checkpoint CORTEX que si ses poids dériventréellement d'un autre modèle — ce qui n'est pas le cas des poids initialisés ici.
## Structure
```textmodel/ définition du modèle et entrées/sorties de checkpointstokenizer/ chargement et validation du tokenizer CORTEXtraining/ boucle d'entraînementdatasets/ datasets de code, avec traçabilité des sources et licencescheckpoints/ checkpoints produits (non versionnés)evaluation/ évaluation : perte, perplexité, générationconfigs/cortex/ configurations d'entraînement```
## Démarrage rapide
```bashpip install torch safetensors tokenizers transformers numpy pytest
# 1. Construire les datasets (traçabilité des licences incluse)python datasets/build.py --all --limit 200
# 2. EntraînerPYTHONPATH=. python3 -c "from training.train import trainprint(train('configs/cortex/cortex-dev-1.json', ['cortex-code-sft'], out_dir='checkpoints/dev', max_steps=100, device='cpu', progress=True))"
# 3. ÉvaluerPYTHONPATH=. python3 -c "import jsonfrom evaluation.evaluate import reportprint(json.dumps(report('checkpoints/dev/final'), indent=2))"
# 4. Tests de cohérencePYTHONPATH=. python3 -m pytest tests/test_cortex_pipeline.py -q```
## Configuration de développement
`configs/cortex/cortex-dev-1.json` décrit un modèle **entraînable** :
| Élément | Valeur ||---|---|| Paramètres | ~174,8 M || Couches | 12 || `hidden_size` | 768 || Têtes d'attention | 12 (4 têtes KV) || Contexte | 2 048 || Vocabulaire | 129 280 (tokenizer CORTEX réutilisé) || Précision | float32 |
Le vocabulaire est repris du tokenizer CORTEX pour que les modèles dedéveloppement partagent le même espace de tokens que la distribution principale.
## État réel
| Étape | État ||---|---|| Audit de l'architecture distribuée | fait — `docs/architecture-technique.fr.md` || Définition du modèle | fait, testée || Tokenizer | fait, validé contre `vocab_size` || Initialisation et checkpoints | fait, testés (manifeste + SHA-256) || Datasets avec licences | fait || Boucle d'entraînement | fait, vérifiée sur CPU || Entraînement complet | **non exécuté** — voir ci-dessous || Remplacement des poids distribués | **non fait, et non prévu** |
### Ce qui a été mesuré
- Les tests de `tests/test_cortex_pipeline.py` passent.- Un entraînement court sur CPU fait **baisser la perte** sur un corpus de code réel (CodeAlpaca), ce qui montre que le pipeline apprend réellement.- Un checkpoint est écrit, son manifeste est vérifié, et une corruption est détectée.
### Ce qui n'a pas été mesuré
- Aucun entraînement long n'a été mené : l'environnement de développement dispose de 4 cœurs CPU, ~15 Gio de RAM et aucun GPU. Les étapes y prennent plusieurs dizaines de secondes, contre quelques millisecondes sur GPU.- Aucune qualité de génération de code n'est revendiquée pour l'instant. Un modèle de 175 M paramètres entraîné quelques centaines d'étapes ne produit pas de code fiable, et ce document ne prétend pas le contraire.
## Feuille de route
1. Entraîner `cortex-dev-1` sur GPU jusqu'à convergence, et publier les courbes réelles.2. Ajouter une évaluation d'exécution (pass@k) sur les tests MBPP, en sandbox.3. Passer à une échelle intermédiaire (~1 B) une fois le pipeline validé.4. Ne toucher à `base_model` et à la présentation publique que lorsque des poids CORTEX réellement entraînés le justifient.1234567891011121314151617181920212223242526272829303132333435363738394041# CORTEX — evaluation
Évaluation des checkpoints CORTEX.
| Fichier | Rôle ||---|---|| `evaluate.py` | perte, perplexité et génération sur un jeu tenu à l'écart |
## Deux mesures
**Perte et perplexité.** Calculées sur les fenêtres de tokens d'un jeu d'évaluation. C'estla mesure la plus fiable disponible ici : elle ne dépend d'aucun test d'exécution etcompare directement le modèle à lui-même au fil de l'entraînement.
**Génération.** Le modèle complète une invite et la sortie est comparée à la référence.Cette mesure est faible et doit être lue comme telle : elle indique si le modèle sedirige vers la bonne réponse, pas si le code est correct.
## Ce qui n'est pas encore mesuré
Aucune évaluation d'exécution (`pass@k`) n'est implémentée. Elle demanderait d'exécuter ducode généré dans un bac à sable, ce qui est un chantier à part entière et n'est pasrevendiqué ici.
## Exemple
```pythonimport jsonfrom evaluation.evaluate import report
print(json.dumps(report("checkpoints/dev/final", limit=20), indent=2))```
## Règle d'honnêteté
Un modèle de développement de ~175 M paramètres entraîné quelques centaines d'étapesproduit du code médiocre. Les rapports affichent les chiffres mesurés sans les arrondirvers le haut, et `report()` inclut une réserve explicite dans le champ `caveat`.
`cortex-code-eval` (HumanEval) est réservé à l'évaluation : l'utiliser pour l'entraînementinvaliderait la mesure. Le registre le signale explicitement.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""CORTEX evaluation.
Evaluation is deliberately separate from training. It answers two questions:
1. Is the model mechanically healthy? (loss on held-out data, perplexity) 2. Can it produce code at all? (exact-match / pass-rate on a held-out set)
The reported numbers are whatever they are. A small development model will scorebadly on HumanEval; that is expected and is reported honestly rather than dressed up."""
from __future__ import annotations
import jsonimport mathfrom pathlib import Path
import torch
from model.cortex_model import CortexConfigfrom training.train import build_token_stream, load_jsonl
__all__ = ["evaluate_loss", "evaluate_generation", "report"]
REPO_ROOT = Path(__file__).resolve().parent.parent
@torch.no_grad()def evaluate_loss(model, token_data: torch.Tensor, batch_size: int = 2, device: str = "cpu") -> dict: """Average cross-entropy over the held-out token windows.""" model.eval().to(device) n = token_data.shape[0] total, count = 0.0, 0 for start in range(0, n, batch_size): batch = token_data[start:start + batch_size].to(device) out = model(batch[:, :-1], labels=batch[:, 1:]) loss = out["loss"].item() total += loss * batch.shape[0] count += batch.shape[0] mean = total / max(count, 1) return { "loss": mean, "perplexity": math.exp(min(mean, 50)), "windows": count, }
@torch.no_grad()def evaluate_generation(model, tokenizer, records: list[dict], limit: int = 20, max_new_tokens: int = 64, device: str = "cpu") -> dict: """Greedy-free sample generation, scored by whether the reference is reproduced.
This is a weak signal on a small model and is reported as such: it measures whether the model can continue a prompt towards the reference solution, not whether the code is correct. """ model.eval().to(device) eos = tokenizer.token_to_id("<|place▁holder▁no▁0|>") or 1 exact, contains, samples = 0, 0, []
for record in records[:limit]: text = record.get("text", "") if "### Response" not in text: continue prompt, reference = text.split("### Response", 1) prompt = prompt + "### Response" ids = torch.tensor([tokenizer.encode(prompt, add_special_tokens=False).ids], device=device) out = model.generate(ids, max_new_tokens=max_new_tokens, temperature=0.0, eos_token_id=eos) generated = tokenizer.decode(out[0][ids.shape[1]:].tolist()) reference = reference.strip() exact += int(generated.strip() == reference) contains += int(reference and reference in generated) samples.append({ "prompt_tail": prompt[-80:].strip(), "generated": generated[:200], "reference": reference[:200], })
n = max(len(samples), 1) return { "samples": samples, "exact_match": exact / n, "reference_contained": contains / n, "n": len(samples), }
def report(checkpoint_dir: str | Path, eval_dataset_id: str = "cortex-code-eval", limit: int = 20, device: str = "cpu") -> dict: """Load a CORTEX checkpoint and produce a full evaluation report.""" from model.init import load_cortex_checkpoint from tokenizer.cortex_tokenizer import load_tokenizer from training.train import load_registry
model, config, provenance = load_cortex_checkpoint(checkpoint_dir) tokenizer = load_tokenizer() registry = load_registry() entry = {d["id"]: d for d in registry["datasets"]}[eval_dataset_id] records = load_jsonl(REPO_ROOT / entry["path"])
token_data = build_token_stream(records, tokenizer, config.max_position_embeddings // 4) loss = evaluate_loss(model, token_data, device=device) generation = evaluate_generation(model, tokenizer, records, limit=limit, device=device)
return { "checkpoint": str(checkpoint_dir), "model_name": config.model_name, "parameters": provenance.get("parameter_count"), "step": provenance.get("step"), "eval_dataset": { "id": eval_dataset_id, "source": entry["source"], "license": entry["license"], }, "loss": loss, "generation": {k: v for k, v in generation.items() if k != "samples"}, "samples": generation["samples"], "caveat": ( "This is a development-scale model. Low scores are expected and are reported " "as measured, not adjusted." ), }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# CORTEX — model
Définition du modèle CORTEX entraînable et gestion des checkpoints.
| Fichier | Rôle ||---|---|| `cortex_model.py` | Architecture : décodeur Transformer, RMSNorm, RoPE, GQA, SwiGLU || `init.py` | Initialisation des poids, écriture et lecture des checkpoints |
## Architecture
`CortexConfig` porte tous les hyper-paramètres. `parameter_breakdown()` calcule le nombrede paramètres de façon analytique, et `count_parameters()` le recompte sur le modèle réel :les deux doivent être égaux, ce que vérifie un test.
Le modèle est un décodeur causal standard :
```texttokens -> embed_tokens -> [N x (RMSNorm -> GQA+RoPE -> résidu -> RMSNorm -> SwiGLU -> résidu)] -> RMSNorm -> lm_head -> logits```
Points d'implémentation à connaître :
- **Perte par blocs.** Le vocabulaire CORTEX compte 129 280 entrées. Un tenseur de logits complet en float32 pour un lot de 2×512 tokens pèserait ~0,5 Go. La perte est donc calculée par tranches (`CortexForCausalLM._loss`), ce qui évite une pointe mémoire qui faisait redémarrer l'environnement de développement.- **Poids liés.** Avec `tie_word_embeddings: true`, `lm_head.weight` **est** `embed_tokens.weight`. `count_parameters` déduplique par identité pour ne pas compter deux fois la même matrice.- **Masque.** En l'absence de `attention_mask`, le masque causal est délégué à `scaled_dot_product_attention`. Un masque de padding est combiné au masque causal.
## Checkpoints
Un checkpoint CORTEX est un dossier auto-descriptif :
```text<checkpoint>/ config.json hyper-paramètres du modèle weights.safetensors provenance.json comment les poids ont été produits optimizer.pt si un optimiseur est fourni manifest.json tailles et SHA-256 de chaque fichier```
`load_cortex_checkpoint()` vérifie le manifeste (taille et SHA-256) **avant** de chargerles poids : un fichier corrompu est refusé, pas silencieusement accepté.
`provenance.json` contient toujours `base_model: null` pour les poids initialisés ici,avec une note explicite. Ce champ ne doit être renseigné que si les poids dériventréellement d'un autre modèle.
## Exemple
```pythonfrom model.cortex_model import CortexConfigfrom model.init import init_cortex_model, save_cortex_checkpoint, load_cortex_checkpoint
config = CortexConfig(model_name="cortex-dev-1")model = init_cortex_model(config, seed=1337)save_cortex_checkpoint(model, config, "checkpoints/demo", step=0)
model, config, provenance = load_cortex_checkpoint("checkpoints/demo")print(provenance["developer"], provenance["base_model"])```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335"""CORTEX model definition — the trainable Frankenstein-Labs architecture.
This module defines the model the CORTEX training pipeline builds and trains. It is astandard decoder-only Transformer with:
* RMSNorm (pre-norm) * rotary position embeddings (RoPE) * grouped-query attention (GQA) * a SwiGLU feed-forward network
Nothing here loads, mutates or depends on the distributed 1.65T checkpoint that thisrepository also hosts. Weights produced from this module are initialised from scratchand are owned by Frankenstein-Labs."""
from __future__ import annotations
import jsonimport mathfrom dataclasses import asdict, dataclassfrom pathlib import Path
import torchimport torch.nn as nnimport torch.nn.functional as F
__all__ = ["CortexConfig", "CortexForCausalLM", "count_parameters"]
@dataclassclass CortexConfig: """Hyper-parameters of a trainable CORTEX model."""
vocab_size: int = 129280 hidden_size: int = 768 num_hidden_layers: int = 12 num_attention_heads: int = 12 num_key_value_heads: int = 4 intermediate_size: int = 2048 hidden_act: str = "silu" max_position_embeddings: int = 2048 rope_theta: float = 10000.0 rms_norm_eps: float = 1e-5 attention_bias: bool = False attention_dropout: float = 0.0 tie_word_embeddings: bool = True initializer_range: float = 0.02 bos_token_id: int = 0 eos_token_id: int = 1 pad_token_id: int = 2 model_name: str = "cortex-dev-1"
@property def head_dim(self) -> int: if self.hidden_size % self.num_attention_heads: raise ValueError( f"hidden_size ({self.hidden_size}) must be divisible by " f"num_attention_heads ({self.num_attention_heads})" ) return self.hidden_size // self.num_attention_heads
def validate(self) -> None: if self.num_attention_heads % self.num_key_value_heads: raise ValueError( f"num_attention_heads ({self.num_attention_heads}) must be a multiple of " f"num_key_value_heads ({self.num_key_value_heads})" ) if self.hidden_size % 2: raise ValueError("hidden_size must be even so RoPE can split the head dimension") if self.head_dim % 2: raise ValueError("head_dim must be even for RoPE") if self.vocab_size <= 0: raise ValueError("vocab_size must be positive") if self.num_hidden_layers <= 0: raise ValueError("num_hidden_layers must be positive")
@classmethod def from_json(cls, path: str | Path) -> "CortexConfig": raw = json.loads(Path(path).read_text(encoding="utf-8")) fields = set(cls.__dataclass_fields__) return cls(**{k: v for k, v in raw.items() if k in fields})
def to_json(self, path: str | Path) -> None: Path(path).write_text( json.dumps(asdict(self), indent=2, ensure_ascii=False) + "\n", encoding="utf-8" )
def parameter_breakdown(self) -> dict: """Analytical parameter count, including norms and (tied) embeddings.""" h = self.hidden_size kv = self.num_key_value_heads * self.head_dim q = self.num_attention_heads * self.head_dim attn = h * q + h * kv * 2 + q * h if self.attention_bias: attn += q + kv * 2 mlp = 3 * h * self.intermediate_size norms = 2 * h per_layer = attn + mlp + norms embeds = self.vocab_size * h if self.tie_word_embeddings else self.vocab_size * h * 2 total = embeds + per_layer * self.num_hidden_layers + h return { "embedding_and_head_shared": self.vocab_size * h, "per_layer_attention": attn, "per_layer_mlp": mlp, "per_layer_norms": norms, "total_per_layer": per_layer, "total_estimated": total, }
class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-5): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor: dtype = x.dtype x = x.float() x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) return x.to(dtype) * self.weight
def build_rope_cache(head_dim: int, max_position_embeddings: int, theta: float, device, dtype): """Precompute cos/sin tables of shape [max_pos, head_dim].""" inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim)) positions = torch.arange(max_position_embeddings, device=device).float() freqs = torch.outer(positions, inv_freq) emb = torch.cat((freqs, freqs), dim=-1) return emb.cos().to(dtype), emb.sin().to(dtype)
def rotate_half(x: torch.Tensor) -> torch.Tensor: half = x.shape[-1] // 2 x1, x2 = x[..., :half], x[..., half:] return torch.cat((-x2, x1), dim=-1)
def apply_rope(q, k, cos, sin): cos = cos.unsqueeze(0).unsqueeze(0) sin = sin.unsqueeze(0).unsqueeze(0) return q * cos + rotate_half(q) * sin, k * cos + rotate_half(k) * sin
class CortexAttention(nn.Module): def __init__(self, config: CortexConfig): super().__init__() self.config = config self.num_heads = config.num_attention_heads self.num_kv_heads = config.num_key_value_heads self.head_dim = config.head_dim self.num_kv_groups = self.num_heads // self.num_kv_heads
self.q_proj = nn.Linear( config.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias ) self.k_proj = nn.Linear( config.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias ) self.v_proj = nn.Linear( config.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias ) self.o_proj = nn.Linear( self.num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias ) self.attention_dropout = config.attention_dropout
def forward(self, hidden_states, cos, sin, attention_mask=None): batch, seq, _ = hidden_states.shape q = self.q_proj(hidden_states).view(batch, seq, self.num_heads, self.head_dim) k = self.k_proj(hidden_states).view(batch, seq, self.num_kv_heads, self.head_dim) v = self.v_proj(hidden_states).view(batch, seq, self.num_kv_heads, self.head_dim)
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) q, k = apply_rope(q, k, cos, sin)
if self.num_kv_groups > 1: k = k.repeat_interleave(self.num_kv_groups, dim=1) v = v.repeat_interleave(self.num_kv_groups, dim=1)
dropout_p = self.attention_dropout if self.training else 0.0 attn = F.scaled_dot_product_attention( q, k, v, attn_mask=attention_mask, dropout_p=dropout_p, is_causal=attention_mask is None, ) attn = attn.transpose(1, 2).reshape(batch, seq, self.num_heads * self.head_dim) return self.o_proj(attn)
class CortexMLP(nn.Module): def __init__(self, config: CortexConfig): super().__init__() self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False) self.act = nn.SiLU() if config.hidden_act == "silu" else nn.GELU()
def forward(self, x): return self.down_proj(self.act(self.gate_proj(x)) * self.up_proj(x))
class CortexDecoderLayer(nn.Module): def __init__(self, config: CortexConfig): super().__init__() self.self_attn = CortexAttention(config) self.mlp = CortexMLP(config) self.input_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps) self.post_attention_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps)
def forward(self, hidden_states, cos, sin, attention_mask=None): residual = hidden_states hidden_states = self.self_attn( self.input_layernorm(hidden_states), cos, sin, attention_mask ) hidden_states = residual + hidden_states
residual = hidden_states hidden_states = self.mlp(self.post_attention_layernorm(hidden_states)) return residual + hidden_states
class CortexForCausalLM(nn.Module): """Decoder-only causal language model, the CORTEX training target."""
def __init__(self, config: CortexConfig): super().__init__() config.validate() self.config = config self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) self.layers = nn.ModuleList( [CortexDecoderLayer(config) for _ in range(config.num_hidden_layers)] ) self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) if config.tie_word_embeddings: self.lm_head.weight = self.embed_tokens.weight self.apply(self._init_weights) for name, param in self.named_parameters(): if name.endswith(("o_proj.weight", "down_proj.weight")): nn.init.normal_( param, mean=0.0, std=config.initializer_range / math.sqrt(2 * config.num_hidden_layers), ) self._rope_cache = None
def _init_weights(self, module): if isinstance(module, nn.Linear): nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
def _rope(self, seq_len, device, dtype): if ( self._rope_cache is None or self._rope_cache[0].shape[0] < seq_len or self._rope_cache[0].device != device ): self._rope_cache = build_rope_cache( self.config.head_dim, self.config.max_position_embeddings, self.config.rope_theta, device, dtype, ) cos, sin = self._rope_cache return cos[:seq_len], sin[:seq_len]
def forward(self, input_ids, attention_mask=None, labels=None): batch, seq = input_ids.shape hidden_states = self.embed_tokens(input_ids) cos, sin = self._rope(seq, input_ids.device, hidden_states.dtype)
causal = None if attention_mask is not None: causal = torch.tril( torch.ones(seq, seq, dtype=torch.bool, device=input_ids.device) )[None, None, :, :] causal = causal & attention_mask[:, None, None, :].bool()
for layer in self.layers: hidden_states = layer(hidden_states, cos, sin, causal)
logits = self.lm_head(self.norm(hidden_states)) loss = None if labels is not None: loss = self._loss(logits, labels) return {"logits": logits, "loss": loss}
@staticmethod def _loss(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: """Cross-entropy computed in chunks over the vocabulary.
A full fp32 logits tensor of [batch*seq, vocab] is several hundred megabytes for the CORTEX vocabulary, so the softmax is done in slices. """ shift_logits = logits[:, :-1] shift_labels = labels[:, 1:] total, count = 0.0, 0 chunk = 8192 flat_logits = shift_logits.reshape(-1, shift_logits.size(-1)) flat_labels = shift_labels.reshape(-1) for start in range(0, flat_labels.size(0), chunk): sl = flat_logits[start:start + chunk].float() lb = flat_labels[start:start + chunk] valid = lb.ne(-100) if not valid.any(): continue total = total + F.cross_entropy(sl, lb, ignore_index=-100, reduction="sum") count += int(valid.sum()) if count == 0: return torch.zeros((), device=logits.device, requires_grad=True) return total / count
@torch.no_grad() def generate(self, input_ids, max_new_tokens=32, temperature=1.0, eos_token_id=None): self.eval() for _ in range(max_new_tokens): ctx = input_ids[:, -self.config.max_position_embeddings:] logits = self.forward(ctx)["logits"][:, -1, :] / max(temperature, 1e-5) probs = torch.softmax(logits.float(), dim=-1) next_id = torch.multinomial(probs, num_samples=1) input_ids = torch.cat([input_ids, next_id], dim=1) if eos_token_id is not None and bool((next_id == eos_token_id).all()): break return input_ids
def count_parameters(model: nn.Module) -> int: """Count unique parameters, so tied weights are not double counted.""" seen, total = set(), 0 for param in model.parameters(): if id(param) in seen: continue seen.add(id(param)) total += param.numel() return total123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214"""CORTEX initialisation and checkpoint I/O.
Creates brand-new CORTEX weights from scratch and writes them as self-describingcheckpoints that record exactly how they were produced.
It never reads, writes or modifies the distributed 1.65T checkpoint that thisrepository also hosts. New CORTEX checkpoints are separate artefacts with their ownprovenance record."""
from __future__ import annotations
import hashlibimport jsonimport platformimport subprocessimport timefrom pathlib import Path
import torch
from model.cortex_model import CortexConfig, CortexForCausalLM, count_parameters
__all__ = [ "init_cortex_model", "save_cortex_checkpoint", "load_cortex_checkpoint", "sha256_file", "checkpoint_provenance",]
CHECKPOINT_FORMAT = "cortex-checkpoint-v1"
def _git_commit() -> str | None: try: out = subprocess.run( ["git", "rev-parse", "HEAD"], cwd=Path(__file__).resolve().parent, capture_output=True, text=True, timeout=10, ) return out.stdout.strip() or None except Exception: return None
def checkpoint_provenance(config: CortexConfig, step: int, extra: dict | None = None) -> dict: """Describe how a checkpoint was produced. Recorded inside every checkpoint.""" record = { "format": CHECKPOINT_FORMAT, "model_name": config.model_name, "developer": "Frankenstein-Labs", "weights": "initialised and trained by Frankenstein-Labs", "base_model": None, "base_model_note": ( "No parent model. These weights are not derived from any other model, so no " "base_model attribution applies." ), "step": step, "created_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "torch_version": torch.__version__, "python_version": platform.python_version(), "source_commit": _git_commit(), "license": "mit", } if extra: record.update(extra) return record
def init_cortex_model(config: CortexConfig, seed: int | None = None) -> CortexForCausalLM: """Create a new CORTEX model with randomly initialised weights.""" if seed is not None: torch.manual_seed(seed) model = CortexForCausalLM(config) model.eval() return model
def sha256_file(path: str | Path, chunk: int = 1 << 20) -> str: h = hashlib.sha256() with open(path, "rb") as fh: while block := fh.read(chunk): h.update(block) return h.hexdigest()
def _split_tied_tensors(state: dict) -> tuple[dict, dict]: """Separate storage-shared tensors so safetensors can write the checkpoint.
``safetensors`` refuses to serialise two keys that point at the same storage, and a tied embedding does exactly that. Only one copy is written; the aliases are recorded and re-expanded on load, so the checkpoint stays lossless without storing the tied matrix twice. """ unique: dict = {} aliases: dict[str, str] = {} by_ptr: dict[int, str] = {} for name, tensor in state.items(): ptr = tensor.data_ptr() if ptr in by_ptr: aliases[name] = by_ptr[ptr] else: by_ptr[ptr] = name unique[name] = tensor return unique, aliases
def save_cortex_checkpoint( model: CortexForCausalLM, config: CortexConfig, out_dir: str | Path, step: int = 0, optimizer: torch.optim.Optimizer | None = None, extra_provenance: dict | None = None,) -> Path: """Write a CORTEX checkpoint directory.
Layout::
<out_dir>/ config.json model hyper-parameters weights.safetensors provenance.json how the weights were produced optimizer.pt only when an optimizer is passed manifest.json sizes and SHA-256 of the files above """ out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True)
config.to_json(out_dir / "config.json")
state = {k: v.detach().cpu() for k, v in model.state_dict().items()} unique, aliases = _split_tied_tensors(state) weights_path = out_dir / "weights.safetensors" try: from safetensors.torch import save_file
save_file(unique, str(weights_path)) except ImportError: # pragma: no cover - fallback when safetensors is absent weights_path = out_dir / "weights.pt" torch.save(state, weights_path)
provenance = checkpoint_provenance(config, step, extra_provenance) provenance["parameter_count"] = count_parameters(model) provenance["tensor_count"] = len(state) provenance["stored_tensors"] = len(unique) provenance["tied_tensors"] = aliases (out_dir / "provenance.json").write_text( json.dumps(provenance, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" )
if optimizer is not None: torch.save(optimizer.state_dict(), out_dir / "optimizer.pt")
manifest = {"format": CHECKPOINT_FORMAT, "files": {}} for name in sorted(p.name for p in out_dir.iterdir() if p.name != "manifest.json"): f = out_dir / name manifest["files"][name] = {"bytes": f.stat().st_size, "sha256": sha256_file(f)} (out_dir / "manifest.json").write_text( json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" ) return out_dir
def load_cortex_checkpoint( ckpt_dir: str | Path, strict: bool = True) -> tuple[CortexForCausalLM, CortexConfig, dict]: """Load a CORTEX checkpoint, verifying its manifest first.""" ckpt_dir = Path(ckpt_dir) manifest_path = ckpt_dir / "manifest.json" if not manifest_path.exists(): raise FileNotFoundError(f"no manifest.json in {ckpt_dir}; not a CORTEX checkpoint")
manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest.get("format") != CHECKPOINT_FORMAT: raise ValueError(f"unknown checkpoint format: {manifest.get('format')!r}")
for name, info in manifest["files"].items(): f = ckpt_dir / name if not f.exists(): raise FileNotFoundError(f"checkpoint file missing: {name}") actual = f.stat().st_size if actual != info["bytes"]: raise ValueError(f"{name}: size {actual} != manifest {info['bytes']}") if sha256_file(f) != info["sha256"]: raise ValueError(f"{name}: sha256 mismatch, checkpoint is corrupted")
config = CortexConfig.from_json(ckpt_dir / "config.json") model = CortexForCausalLM(config)
weights = ckpt_dir / "weights.safetensors" if weights.exists(): from safetensors.torch import load_file
state = load_file(str(weights)) else: state = torch.load(ckpt_dir / "weights.pt", map_location="cpu", weights_only=True)
provenance = json.loads((ckpt_dir / "provenance.json").read_text(encoding="utf-8"))
# re-expand tied tensors: they were stored once and aliased, and must be written back # into the state_dict under their original names before loading. for alias, target in (provenance.get("tied_tensors") or {}).items(): if target not in state: raise ValueError(f"checkpoint declares {alias} tied to missing tensor {target}") state[alias] = state[target]
missing, unexpected = model.load_state_dict(state, strict=strict) if strict and (missing or unexpected): raise ValueError(f"state_dict mismatch: missing={missing} unexpected={unexpected}") model.eval()
return model, config, provenance123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322"""Coherence tests for the CORTEX model, tokenizer and checkpoints.
These tests exercise real code paths: they build real models, run real forward andbackward passes, write real checkpoints to disk and read them back. Nothing is mocked.
Run with::
PYTHONPATH=. python3 -m pytest tests/test_cortex_pipeline.py -q"""
from __future__ import annotations
import jsonfrom pathlib import Path
import pytestimport torch
from model.cortex_model import CortexConfig, CortexForCausalLM, count_parametersfrom model.init import ( CHECKPOINT_FORMAT, init_cortex_model, load_cortex_checkpoint, save_cortex_checkpoint, sha256_file,)from tokenizer.cortex_tokenizer import ( assert_vocab_matches_config, describe_tokenizer, load_tokenizer,)
REPO_ROOT = Path(__file__).resolve().parent.parent
@pytest.fixture(scope="module")def small_config() -> CortexConfig: """A tiny model that trains in milliseconds but exercises every code path.""" return CortexConfig( vocab_size=129280, hidden_size=64, num_hidden_layers=2, num_attention_heads=4, num_key_value_heads=2, intermediate_size=128, max_position_embeddings=64, model_name="cortex-test", )
# --------------------------------------------------------------------------- model
def test_parameter_count_matches_analytical(small_config): model = CortexForCausalLM(small_config) assert count_parameters(model) == small_config.parameter_breakdown()["total_estimated"]
def test_tied_embeddings_share_storage(small_config): model = CortexForCausalLM(small_config) assert small_config.tie_word_embeddings assert model.lm_head.weight is model.embed_tokens.weight
def test_untied_embeddings_are_separate(small_config): cfg = CortexConfig(**{**small_config.__dict__, "tie_word_embeddings": False}) model = CortexForCausalLM(cfg) assert model.lm_head.weight is not model.embed_tokens.weight # two embedding matrices now, so the count must be larger assert count_parameters(model) > small_config.parameter_breakdown()["total_estimated"]
def test_forward_shapes(small_config): model = CortexForCausalLM(small_config) ids = torch.randint(0, small_config.vocab_size, (2, 16)) out = model(ids) assert out["logits"].shape == (2, 16, small_config.vocab_size) assert out["loss"] is None
def test_loss_is_finite_and_backward_works(small_config): model = CortexForCausalLM(small_config) ids = torch.randint(0, small_config.vocab_size, (2, 16)) out = model(ids, labels=ids) assert torch.isfinite(out["loss"]) out["loss"].backward() grads = [p.grad for p in model.parameters() if p.grad is not None] assert grads and all(torch.isfinite(g).all() for g in grads)
def test_causal_mask_hides_future_tokens(small_config): """Changing a future token must not change an earlier position's logits.""" model = CortexForCausalLM(small_config).eval() ids = torch.randint(0, small_config.vocab_size, (1, 8)) modified = ids.clone() modified[0, -1] = (modified[0, -1] + 1) % small_config.vocab_size with torch.no_grad(): a = model(ids)["logits"][0, :-1] b = model(modified)["logits"][0, :-1] assert torch.allclose(a, b, atol=1e-5)
def test_padding_mask_blocks_padded_positions(small_config): model = CortexForCausalLM(small_config).eval() ids = torch.randint(0, small_config.vocab_size, (1, 8)) mask = torch.tensor([[1, 1, 1, 1, 1, 0, 0, 0]]) with torch.no_grad(): out = model(ids, attention_mask=mask)["logits"] assert torch.isfinite(out).all()
def test_invalid_config_is_rejected(): with pytest.raises(ValueError): CortexConfig(hidden_size=65, num_attention_heads=5, num_key_value_heads=5).validate() with pytest.raises(ValueError): CortexConfig(hidden_size=64, num_attention_heads=6, num_key_value_heads=4).validate()
def test_greedy_generation_stays_in_vocab(small_config): model = CortexForCausalLM(small_config).eval() ids = torch.randint(0, small_config.vocab_size, (1, 4)) out = model.generate(ids, max_new_tokens=5, temperature=0.0) assert out.shape == (1, 9) assert int(out.max()) < small_config.vocab_size
def test_config_roundtrip(tmp_path, small_config): path = tmp_path / "config.json" small_config.to_json(path) assert CortexConfig.from_json(path) == small_config
# ----------------------------------------------------------------------- tokenizer
def test_tokenizer_vocab_matches_cortex_config(): tokenizer = load_tokenizer() assert_vocab_matches_config(tokenizer, 129280)
def test_tokenizer_counters_are_consistent(): facts = describe_tokenizer() assert facts["base_vocab_size"] == 128000 assert facts["added_tokens"] == 1283 # ids 0, 1, 2 appear in both the base vocab and the added tokens assert facts["overlapping_ids"] == 3 assert facts["unique_ids"] == 129280 assert facts["base_vocab_size"] + facts["added_tokens"] - facts["overlapping_ids"] == 129280
def test_tokenizer_roundtrip_preserves_code(): tokenizer = load_tokenizer() code = "def add(a, b):\n return a + b\n" assert tokenizer.decode(tokenizer.encode(code).ids) == code
def test_vocab_mismatch_is_rejected(): tokenizer = load_tokenizer() with pytest.raises(ValueError, match="vocab_size"): assert_vocab_matches_config(tokenizer, 1000)
# --------------------------------------------------------------------- checkpoints
def test_checkpoint_roundtrip_preserves_weights(tmp_path, small_config): model = init_cortex_model(small_config, seed=7) ckpt = save_cortex_checkpoint(model, small_config, tmp_path / "ckpt", step=3)
loaded, cfg, provenance = load_cortex_checkpoint(ckpt) assert cfg == small_config assert provenance["step"] == 3 assert provenance["format"] == CHECKPOINT_FORMAT for (n1, p1), (n2, p2) in zip( model.state_dict().items(), loaded.state_dict().items() ): assert n1 == n2 assert torch.equal(p1, p2)
def test_checkpoint_stores_tied_weights_once(tmp_path, small_config): """A tied embedding must be written once, not duplicated, and still load back.""" model = init_cortex_model(small_config, seed=5) ckpt = save_cortex_checkpoint(model, small_config, tmp_path / "ckpt") provenance = json.loads((ckpt / "provenance.json").read_text(encoding="utf-8")) assert provenance["tied_tensors"] == {"lm_head.weight": "embed_tokens.weight"} assert provenance["stored_tensors"] < provenance["tensor_count"]
loaded, _, _ = load_cortex_checkpoint(ckpt) assert torch.equal(loaded.embed_tokens.weight, loaded.lm_head.weight) assert torch.equal(loaded.embed_tokens.weight, model.embed_tokens.weight)
def test_checkpoint_records_no_false_base_model(tmp_path, small_config): """A from-scratch CORTEX checkpoint must not claim a parent model.""" model = init_cortex_model(small_config, seed=1) ckpt = save_cortex_checkpoint(model, small_config, tmp_path / "ckpt") provenance = json.loads((ckpt / "provenance.json").read_text(encoding="utf-8")) assert provenance["base_model"] is None assert provenance["developer"] == "Frankenstein-Labs" assert "trained by Frankenstein-Labs" in provenance["weights"]
def test_checkpoint_manifest_lists_every_file(tmp_path, small_config): model = init_cortex_model(small_config, seed=1) ckpt = save_cortex_checkpoint(model, small_config, tmp_path / "ckpt") manifest = json.loads((ckpt / "manifest.json").read_text(encoding="utf-8")) on_disk = {p.name for p in ckpt.iterdir() if p.name != "manifest.json"} assert set(manifest["files"]) == on_disk for name, info in manifest["files"].items(): assert info["sha256"] == sha256_file(ckpt / name)
def test_corrupted_checkpoint_is_detected(tmp_path, small_config): model = init_cortex_model(small_config, seed=1) ckpt = save_cortex_checkpoint(model, small_config, tmp_path / "ckpt") weights = ckpt / "weights.safetensors" if not weights.exists(): pytest.skip("safetensors not installed; pointer fallback in use") raw = bytearray(weights.read_bytes()) raw[-1] ^= 0xFF weights.write_bytes(bytes(raw)) with pytest.raises(ValueError, match="sha256 mismatch"): load_cortex_checkpoint(ckpt)
def test_missing_manifest_is_rejected(tmp_path, small_config): empty = tmp_path / "not-a-checkpoint" empty.mkdir() with pytest.raises(FileNotFoundError, match="manifest.json"): load_cortex_checkpoint(empty)
def test_checkpoint_is_reproducible_from_seed(tmp_path, small_config): a = init_cortex_model(small_config, seed=42) b = init_cortex_model(small_config, seed=42) for (_, p1), (_, p2) in zip(a.state_dict().items(), b.state_dict().items()): assert torch.equal(p1, p2)
def test_different_seeds_give_different_weights(small_config): a = init_cortex_model(small_config, seed=1) b = init_cortex_model(small_config, seed=2) assert not torch.equal(a.embed_tokens.weight, b.embed_tokens.weight)
# ------------------------------------------------------------------- training data
def test_training_refuses_undeclared_dataset(): from training.train import assert_dataset_usable, load_registry
registry = load_registry() with pytest.raises(KeyError, match="not declared"): assert_dataset_usable(registry, "does-not-exist")
def test_training_refuses_unlicensed_dataset(): from training.train import assert_dataset_usable
registry = {"datasets": [{ "id": "bad", "source": "x", "license": "unknown", "license_url": "x", "origin": "x", "redistribution": "no", }]} with pytest.raises(ValueError, match="refusing to train"): assert_dataset_usable(registry, "bad")
def test_every_registered_dataset_has_license_and_origin(): from training.train import load_registry
for entry in load_registry()["datasets"]: assert entry["license"], entry["id"] assert entry["origin"], entry["id"] assert entry["license_url"], entry["id"] assert entry["license"].lower() not in {"unknown", "none", "proprietary"}, entry["id"]
def test_dataset_metadata_files_match_their_jsonl(): from training.train import load_registry
for entry in load_registry()["datasets"]: jsonl = REPO_ROOT / entry["path"] meta_path = jsonl.with_suffix(".meta.json") if not jsonl.exists() or not meta_path.exists(): continue meta = json.loads(meta_path.read_text(encoding="utf-8")) assert meta["jsonl_sha256"] == sha256_file(jsonl), entry["id"] assert meta["license"] == entry["license"], entry["id"]
def test_build_token_stream_produces_full_windows(small_config): from training.train import build_token_stream
tokenizer = load_tokenizer() records = [{"text": "def f():\n return 1\n"}] * 40 data = build_token_stream(records, tokenizer, seq_len=32) assert data.ndim == 2 assert data.shape[1] == 33 assert int(data.max()) < small_config.vocab_size
def test_training_step_reduces_loss_on_a_tiny_corpus(): """Overfit a tiny corpus: if the pipeline works, loss must drop sharply.""" from training.train import CortexTrainer, build_token_stream
cfg = CortexConfig( vocab_size=129280, hidden_size=64, num_hidden_layers=2, num_attention_heads=4, num_key_value_heads=2, intermediate_size=128, max_position_embeddings=64, ) tokenizer = load_tokenizer() records = [{"text": "def add(a, b):\n return a + b\n"}] * 64 data = build_token_stream(records, tokenizer, seq_len=32) model = init_cortex_model(cfg, seed=0) train_cfg = { "micro_batch_size": 2, "gradient_accumulation_steps": 1, "learning_rate": 3e-3, "min_learning_rate": 3e-4, "weight_decay": 0.0, "beta1": 0.9, "beta2": 0.95, "grad_clip": 1.0, "warmup_steps": 1, "max_steps": 40, "seed": 0, "log_every": 1, "save_every": 0, "sequence_length": 32, } trainer = CortexTrainer(model, cfg, tokenizer, data, train_cfg, device="cpu") history = trainer.train(max_steps=40, log_every=1) first = sum(h["loss"] for h in history[:3]) / 3 last = sum(h["loss"] for h in history[-3:]) / 3 assert last < first, f"loss did not fall: {first} -> {last}"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253# CORTEX — tokenizer
Le tokenizer CORTEX est **réutilisé tel quel** depuis le dépôt distribué(`Frankenstein-Labs/Cortex-ai`), sous licence MIT. Il n'est ni reconstruit, ni modifié.
| Fichier | Rôle ||---|---|| `../tokenizer.json` | tokenizer distribué, à la racine du dépôt (BPE, 129 280 identifiants) || `cortex_tokenizer.py` | chargement et validation |
## Chiffres mesurés
| Propriété | Valeur ||---|---|| Classe | `PreTrainedTokenizerFast` || Modèle | BPE || Vocabulaire de base | 128 000 || Fusions | 127 741 || Tokens ajoutés | 1 283 || Identifiants uniques | **129 280** || Identifiants en doublon | 3 (ids 0, 1, 2) |
## Le piège du décompte
`128 000 + 1 283 = 129 283`, mais `config.json` déclare `vocab_size: 129280` et lesembeddings ont 129 280 lignes.
Ce n'est pas une incohérence : les identifiants 0, 1 et 2 (`bos`, `eos`, `pad`)apparaissent **à la fois** comme tokens spéciaux ajoutés et comme entrées du vocabulaireBPE. Le nombre d'identifiants **uniques** est bien 129 280.
C'est pourquoi `assert_vocab_matches_config()` compare les identifiants uniques et jamaisles compteurs bruts. Toute réutilisation de ce tokenizer doit faire de même.
## Exemple
```pythonfrom tokenizer.cortex_tokenizer import load_tokenizer, assert_vocab_matches_config
tokenizer = load_tokenizer()assert_vocab_matches_config(tokenizer, 129280)print(tokenizer.decode(tokenizer.encode("def add(a, b):\n return a + b\n").ids))```
## Si le fichier est absent
`tokenizer.json` est versionné **à la racine** du dépôt, et le pipeline le charge depuis là :une seule copie existe, donc aucune divergence n'est possible entre le tokenizer du pipeline etcelui du checkpoint distribué. S'il manque, le récupérer depuis la source :
```bashhf download Frankenstein-Labs/Cortex-ai tokenizer.json --local-dir .```12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""CORTEX tokenizer — loading and validating the CORTEX vocabulary.
The CORTEX tokenizer is reused unchanged from the distributed repository(``Frankenstein-Labs/Cortex-ai``, MIT). This module never rebuilds or mutates it; itloads the shipped ``tokenizer.json`` and exposes helpers used by the pipeline."""
from __future__ import annotations
import jsonfrom pathlib import Path
from tokenizers import Tokenizer
__all__ = ["load_tokenizer", "describe_tokenizer", "assert_vocab_matches_config"]
DEFAULT_TOKENIZER = Path(__file__).resolve().parent.parent / "tokenizer.json"
def load_tokenizer(path: str | Path | None = None) -> Tokenizer: """Load the CORTEX BPE tokenizer.
Defaults to the ``tokenizer.json`` shipped at the repository root, so the pipeline and the distributed checkpoint use one and the same vocabulary file. """ path = Path(path) if path else DEFAULT_TOKENIZER if not path.exists(): raise FileNotFoundError( f"tokenizer not found at {path}. See tokenizer/README.md for how it is obtained." ) return Tokenizer.from_file(str(path))
def describe_tokenizer(path: str | Path | None = None) -> dict: """Return measured facts about the tokenizer file.""" path = Path(path) if path else DEFAULT_TOKENIZER raw = json.loads(path.read_text(encoding="utf-8")) model = raw.get("model", {}) added = raw.get("added_tokens", []) vocab_size = len(model.get("vocab", {})) added_ids = {t["id"] for t in added} base_ids = set(range(vocab_size)) return { "tokenizer_class": raw.get("tokenizer_class", "PreTrainedTokenizerFast"), "model_type": model.get("type"), "base_vocab_size": vocab_size, "merges": len(model.get("merges", [])), "added_tokens": len(added), "unique_ids": len(base_ids | added_ids), "overlapping_ids": len(base_ids & added_ids), "max_added_id": max(added_ids) if added_ids else None, }
def assert_vocab_matches_config(tokenizer: Tokenizer, vocab_size: int) -> None: """Fail loudly if the tokenizer and the model disagree on vocabulary size.
The CORTEX tokenizer exposes 128000 BPE entries plus 1283 added tokens, but ids 0, 1 and 2 appear in both sets. The number of *unique* ids is what must equal ``vocab_size``, so raw counters must never be compared directly. """ unique = tokenizer.get_vocab_size(with_added_tokens=True) if unique != vocab_size: raise ValueError( f"tokenizer exposes {unique} unique ids but the model config declares " f"vocab_size={vocab_size}" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# CORTEX — training
Boucle d'entraînement des poids CORTEX.
| Fichier | Rôle ||---|---|| `train.py` | Chargement des données, boucle d'entraînement, planification du taux d'apprentissage |
## Ce que fait la boucle
1. Vérifie chaque dataset contre `datasets/registry.json` (source et licence déclarées).2. Charge le tokenizer CORTEX et vérifie qu'il correspond à `vocab_size`.3. Concatène les enregistrements en un flux de tokens, découpé en fenêtres de longueur fixe.4. Initialise les poids depuis la graine de la configuration.5. Entraîne avec AdamW, décroissance cosinus, échauffement linéaire et écrêtage du gradient.6. Écrit des checkpoints intermédiaires et un checkpoint final, chacun avec sa provenance.
## Le garde-fou des licences
`assert_dataset_usable()` refuse tout dataset :
- absent de `registry.json` ;- sans `source`, `origin`, `license` ou `license_url` ;- dont la licence vaut `unknown`, `none` ou `proprietary`.
Ce contrôle est volontairement bloquant. Un dataset non traçable ne peut pas entrer dansCORTEX, même par erreur de configuration.
## Exemple
```pythonfrom training.train import train
result = train( config_path="configs/cortex/cortex-dev-1.json", dataset_ids=["cortex-code-sft"], out_dir="checkpoints/dev", max_steps=200, device="cpu", progress=True,)print(result["final_loss"], result["checkpoint"])```
## Options de la boucle
| Paramètre | Effet ||---|---|| `max_steps` | nombre d'étapes d'optimisation || `save_every` | fréquence des checkpoints intermédiaires (0 = aucun) || `log_every` | fréquence des lignes de journal || `seed` | force la graine d'initialisation || `device` | `cpu` ou `cuda` |
## Reprise après interruption
Chaque checkpoint contient `optimizer.pt` lorsqu'un optimiseur est fourni à`save_cortex_checkpoint`. La reprise automatique n'est pas encore implémentée : ellesuppose de recharger l'état de l'optimiseur et la position dans les données, ce qui resteà faire.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237"""CORTEX training pipeline.
Trains a CORTEX model from scratch on code and instruction data. Every dataset must bedeclared in ``datasets/registry.json`` together with its source and license; the trainerrefuses to run on an undeclared or license-incompatible dataset."""
from __future__ import annotations
import jsonimport mathfrom dataclasses import dataclassfrom pathlib import Path
import torch
from model.cortex_model import CortexConfig, count_parameters
__all__ = ["load_registry", "load_jsonl", "CortexTrainer", "train"]
REPO_ROOT = Path(__file__).resolve().parent.parent
def load_registry(path: str | Path | None = None) -> dict: path = Path(path) if path else REPO_ROOT / "datasets" / "registry.json" return json.loads(path.read_text(encoding="utf-8"))
def load_jsonl(path: str | Path) -> list[dict]: records = [] with open(path, encoding="utf-8") as fh: for line in fh: line = line.strip() if line: records.append(json.loads(line)) return records
def assert_dataset_usable(registry: dict, dataset_id: str) -> dict: """Refuse datasets whose license or provenance is not declared.
This is the gate that keeps unlicensed or untraceable data out of CORTEX. """ entries = {d["id"]: d for d in registry["datasets"]} if dataset_id not in entries: raise KeyError(f"dataset {dataset_id!r} is not declared in the registry") entry = entries[dataset_id] for field in ("source", "license", "license_url", "origin", "redistribution"): if not entry.get(field): raise ValueError(f"dataset {dataset_id!r} has no {field!r}; refusing to train on it") if entry["license"].lower() in {"unknown", "none", "proprietary"}: raise ValueError( f"dataset {dataset_id!r} has license {entry['license']!r}; refusing to train on it" ) return entry
def build_token_stream(records: list[dict], tokenizer, seq_len: int): """Turn records into a flat token tensor cut into fixed-length windows.""" ids: list[int] = [] eos = tokenizer.token_to_id("<|place▁holder▁no▁0|>") if eos is None: eos = 1 for r in records: text = r.get("text") if text is None: prompt, completion = r.get("prompt", ""), r.get("completion", "") text = f"{prompt}\n{completion}" if (prompt or completion) else "" if not text: continue ids.extend(tokenizer.encode(text, add_special_tokens=False).ids) ids.append(eos) if len(ids) < seq_len + 1: raise ValueError(f"not enough tokens: {len(ids)} for seq_len={seq_len}") n_windows = len(ids) // (seq_len + 1) tensor = torch.tensor(ids[: n_windows * (seq_len + 1)], dtype=torch.long) return tensor.view(n_windows, seq_len + 1)
@dataclassclass TrainState: step: int = 0 tokens_seen: int = 0 best_loss: float = float("inf")
class CortexTrainer: def __init__(self, model, config: CortexConfig, tokenizer, token_data: torch.Tensor, train_cfg: dict, device: str = "cpu"): self.model = model.to(device) self.config = config self.tokenizer = tokenizer self.data = token_data self.cfg = train_cfg self.device = device self.state = TrainState()
decay, no_decay = [], [] for _, p in model.named_parameters(): if not p.requires_grad: continue (no_decay if p.ndim < 2 else decay).append(p) self.optimizer = torch.optim.AdamW( [ {"params": decay, "weight_decay": train_cfg["weight_decay"]}, {"params": no_decay, "weight_decay": 0.0}, ], lr=train_cfg["learning_rate"], betas=(train_cfg["beta1"], train_cfg["beta2"]), )
def lr_at(self, step: int) -> float: warmup, total = self.cfg["warmup_steps"], self.cfg["max_steps"] base, floor = self.cfg["learning_rate"], self.cfg["min_learning_rate"] if step < warmup: return base * (step + 1) / max(warmup, 1) progress = (step - warmup) / max(total - warmup, 1) return floor + 0.5 * (base - floor) * (1 + math.cos(math.pi * min(progress, 1.0)))
def train(self, max_steps: int | None = None, on_step=None, on_save=None, save_every: int | None = None, log_every: int | None = None): self.model.train() max_steps = max_steps or self.cfg["max_steps"] save_every = save_every or self.cfg["save_every"] log_every = log_every or self.cfg["log_every"] bs = self.cfg["micro_batch_size"] accum = self.cfg["gradient_accumulation_steps"] seq_len = self.cfg["sequence_length"]
n_windows = self.data.shape[0] g = torch.Generator().manual_seed(self.cfg["seed"]) history = []
while self.state.step < max_steps: self.optimizer.zero_grad(set_to_none=True) accum_loss = 0.0 for _ in range(accum): idx = torch.randint(0, n_windows, (bs,), generator=g) batch = self.data[idx].to(self.device) inputs, labels = batch[:, :-1], batch[:, 1:].clone() loss = self.model(inputs, labels=labels)["loss"] / accum loss.backward() accum_loss += loss.item() torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.cfg["grad_clip"]) lr = self.lr_at(self.state.step) for group in self.optimizer.param_groups: group["lr"] = lr self.optimizer.step()
self.state.step += 1 self.state.tokens_seen += bs * accum * seq_len self.state.best_loss = min(self.state.best_loss, accum_loss)
if log_every and self.state.step % log_every == 0: history.append({"step": self.state.step, "loss": accum_loss, "lr": lr}) if on_step: on_step(self.state.step, accum_loss, lr) if save_every and self.state.step % save_every == 0 and on_save: on_save(self.state.step, self.state.best_loss)
self.model.eval() return history
def train(config_path, dataset_ids, tokenizer_path=None, out_dir="checkpoints/dev", max_steps=None, device="cpu", registry_path=None, seed=None, progress=False, save_every=None, log_every=None): """End-to-end training entry point used by the CLI.""" from model.init import init_cortex_model, save_cortex_checkpoint from tokenizer.cortex_tokenizer import load_tokenizer, assert_vocab_matches_config
raw = json.loads(Path(config_path).read_text(encoding="utf-8")) config = CortexConfig.from_json(config_path) config_seed = seed if seed is not None else raw.get("training", {}).get("seed", 1337)
registry = load_registry(registry_path) records = [] for dataset_id in dataset_ids: entry = assert_dataset_usable(registry, dataset_id) ds_path = REPO_ROOT / entry["path"] if not ds_path.exists(): raise FileNotFoundError( f"dataset {dataset_id!r} declared at {entry['path']} is not present. " f"See datasets/README.md for how it is built." ) records.extend(load_jsonl(ds_path))
tokenizer = load_tokenizer(tokenizer_path) assert_vocab_matches_config(tokenizer, config.vocab_size)
train_cfg = dict(raw["training"]) if max_steps: train_cfg["max_steps"] = max_steps token_data = build_token_stream(records, tokenizer, train_cfg["sequence_length"])
model = init_cortex_model(config, seed=config_seed) trainer = CortexTrainer(model, config, tokenizer, token_data, train_cfg, device=device)
def dataset_provenance(): return [ {"id": d, "license": assert_dataset_usable(registry, d)["license"], "source": assert_dataset_usable(registry, d)["source"]} for d in dataset_ids ]
def on_step(step, loss, lr): if progress: print(f"step {step:>6} loss {loss:.4f} lr {lr:.2e}", flush=True)
def on_save(step, best): save_cortex_checkpoint( model, config, Path(out_dir) / f"step-{step}", step=step, extra_provenance={"datasets": dataset_provenance(), "training_config": train_cfg}, ) if progress: print(f" saved checkpoint at step {step}", flush=True)
history = trainer.train(max_steps=max_steps, on_step=on_step, on_save=on_save, save_every=save_every, log_every=log_every)
final_dir = save_cortex_checkpoint( model, config, Path(out_dir) / "final", step=trainer.state.step, extra_provenance={ "datasets": dataset_provenance(), "training_config": train_cfg, "tokens_seen": trainer.state.tokens_seen, "final_loss": history[-1]["loss"] if history else None, }, ) return { "checkpoint": str(final_dir), "steps": trainer.state.step, "tokens_seen": trainer.state.tokens_seen, "final_loss": history[-1]["loss"] if history else None, "parameters": count_parameters(model), "history": history, }