Upload 4 files
Browse filesFiles changed (4)
- data/__init__.pyAdded+4
- data/dataset.pyAdded+295
- data/sample_dataset.jsonlAdded+10
- data/tokenizer.pyAdded+334
1234"""Shulker Code — Data Package"""from data.tokenizer import ShulkerTokenizerfrom data.dataset import CodeTokenDataset, StreamingCodeDataset, create_dataloader, discover_code_files__all__ = ["ShulkerTokenizer","CodeTokenDataset","StreamingCodeDataset","create_dataloader","discover_code_files"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295"""===================================== Shulker Code — Dataset Module Code dataset loaders for training Developed by @kopeedev / CyeroX=====================================
Supported formats: - JSONL: {"text": "...", "lang": "python"} or {"prompt": "...", "completion": "..."} - TXT: Plain code files - HuggingFace datasets (GitHub Code, CodeSearchNet, etc.)"""
import osimport jsonimport globimport randomfrom typing import Optional, List, Dict, Iterator, Unionfrom pathlib import Path
import torchfrom torch.utils.data import Dataset, DataLoader, IterableDataset
# ─────────────────────────────────────────────# Core Token Dataset# ─────────────────────────────────────────────class CodeTokenDataset(Dataset): """ Dataset that loads pre-tokenized code sequences from JSONL files.
Each sample in the JSONL can have: - {"text": "..."} → raw code/text to tokenize - {"input_ids": [1, 2, ...]} → pre-tokenized (faster) - {"prompt": "...", "completion": "..."} → instruction format
Uses sliding window to handle long files. """
def __init__( self, file_paths: Union[str, List[str]], tokenizer, max_seq_len: int = 1024, stride: int = 512, # Sliding window stride task: str = "gen", language: str = "python", cache_tokenized: bool = True, ): self.tokenizer = tokenizer self.max_seq_len = max_seq_len self.stride = stride self.task = task self.language = language
# Normalize to list if isinstance(file_paths, str): file_paths = [file_paths]
# Load all samples self.samples: List[List[int]] = [] self._load_files(file_paths, cache_tokenized)
print(f"📦 Dataset loaded: {len(self.samples):,} sequences from {len(file_paths)} files")
def _load_files(self, file_paths: List[str], cache_tokenized: bool): """Load and tokenize all files.""" for path in file_paths: if not os.path.exists(path): print(f"⚠️ File not found: {path}") continue
ext = Path(path).suffix.lower()
if ext in (".jsonl", ".json"): self._load_jsonl(path) elif ext in (".txt", ".py", ".js", ".ts", ".cpp", ".java", ".go", ".rs"): self._load_text_file(path) else: # Try as text self._load_text_file(path)
def _load_jsonl(self, path: str): """Load a JSONL file.""" with open(path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: item = json.loads(line) self._add_item(item) except json.JSONDecodeError: continue
def _load_text_file(self, path: str): """Load a plain text/code file.""" with open(path, "r", encoding="utf-8", errors="replace") as f: text = f.read()
# Detect language from extension ext_to_lang = {".py": "python", ".js": "javascript", ".ts": "typescript", ".cpp": "cpp", ".java": "java", ".go": "go", ".rs": "rust"} lang = ext_to_lang.get(Path(path).suffix.lower(), "text")
self._add_text(text, lang)
def _add_item(self, item: Dict): """Process a single dataset item.""" if "input_ids" in item: # Already tokenized ids = item["input_ids"] self._add_ids(ids) elif "text" in item: lang = item.get("lang", self.language) self._add_text(item["text"], lang) elif "prompt" in item and "completion" in item: # Instruction-following format text = item["prompt"] + item["completion"] lang = item.get("lang", self.language) self._add_text(text, lang) elif "content" in item: # GitHub Code format lang = item.get("programming_language", self.language) self._add_text(item["content"], lang)
def _add_text(self, text: str, lang: str = "python"): """Tokenize text and add as sliding window chunks.""" try: ids = self.tokenizer.encode_code(text, language=lang, task=self.task) self._add_ids(ids) except Exception: # Fallback: basic encode try: ids = self.tokenizer.encode(text) self._add_ids(ids) except Exception: pass
def _add_ids(self, ids: List[int]): """Split token sequence into overlapping windows.""" if len(ids) < 2: return
# Slide a window over the sequence for start in range(0, max(1, len(ids) - self.max_seq_len + 1), self.stride): chunk = ids[start : start + self.max_seq_len] if len(chunk) >= 2: # Need at least 2 tokens for input/label pairs self.samples.append(chunk)
def __len__(self) -> int: return len(self.samples)
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]: ids = self.samples[idx]
# Pad to max_seq_len pad_len = self.max_seq_len - len(ids) attention_mask = [1] * len(ids) + [0] * pad_len ids = ids + [self.tokenizer.pad_token_id] * pad_len
return { "input_ids": torch.tensor(ids, dtype=torch.long), "attention_mask": torch.tensor(attention_mask, dtype=torch.long), "labels": torch.tensor(ids, dtype=torch.long), # Same as input for CLM }
# ─────────────────────────────────────────────# Streaming Dataset (for huge datasets)# ─────────────────────────────────────────────class StreamingCodeDataset(IterableDataset): """ Streaming dataset for training on massive code corpora. Reads from disk on-the-fly without loading everything into RAM. Perfect for datasets like GitHub Code (hundreds of GB). """
def __init__( self, file_paths: List[str], tokenizer, max_seq_len: int = 1024, shuffle: bool = True, buffer_size: int = 1000, ): self.file_paths = file_paths self.tokenizer = tokenizer self.max_seq_len = max_seq_len self.shuffle = shuffle self.buffer_size = buffer_size
def __iter__(self) -> Iterator[Dict[str, torch.Tensor]]: files = self.file_paths.copy() if self.shuffle: random.shuffle(files)
buffer = []
for path in files: with open(path, "r", encoding="utf-8", errors="replace") as f: for line in f: line = line.strip() if not line: continue try: item = json.loads(line) text = item.get("text") or item.get("content") or item.get("code", "") lang = item.get("lang", "python") except Exception: text = line lang = "python"
if not text: continue
try: ids = self.tokenizer.encode_code(text, language=lang) except Exception: continue
# Yield chunks for start in range(0, max(1, len(ids) - self.max_seq_len + 1), self.max_seq_len // 2): chunk = ids[start : start + self.max_seq_len] if len(chunk) < 2: continue
pad_len = self.max_seq_len - len(chunk) attention_mask = [1] * len(chunk) + [0] * pad_len chunk = chunk + [self.tokenizer.pad_token_id] * pad_len
sample = { "input_ids": torch.tensor(chunk, dtype=torch.long), "attention_mask": torch.tensor(attention_mask, dtype=torch.long), "labels": torch.tensor(chunk, dtype=torch.long), }
buffer.append(sample)
if self.shuffle and len(buffer) >= self.buffer_size: random.shuffle(buffer) yield from buffer buffer = []
# Yield remaining if self.shuffle: random.shuffle(buffer) yield from buffer
# ─────────────────────────────────────────────# DataLoader Factory# ─────────────────────────────────────────────def create_dataloader( dataset: Dataset, batch_size: int = 8, num_workers: int = 4, shuffle: bool = True, pin_memory: bool = True, drop_last: bool = True,) -> DataLoader: """Create an optimized DataLoader for training.""" return DataLoader( dataset, batch_size=batch_size, shuffle=shuffle and not isinstance(dataset, IterableDataset), num_workers=num_workers, pin_memory=pin_memory and torch.cuda.is_available(), drop_last=drop_last, persistent_workers=num_workers > 0, prefetch_factor=2 if num_workers > 0 else None, )
def discover_code_files(directory: str, extensions: Optional[List[str]] = None) -> List[str]: """ Recursively find all code files in a directory.
Args: directory: Root directory to search extensions: List of extensions, e.g. [".py", ".js"]
Returns: List of file paths """ if extensions is None: extensions = [".py", ".js", ".ts", ".cpp", ".java", ".go", ".rs", ".cs", ".txt", ".jsonl"]
files = [] for ext in extensions: pattern = os.path.join(directory, "**", f"*{ext}") files.extend(glob.glob(pattern, recursive=True))
print(f"🔍 Found {len(files):,} code files in {directory}") return files12345678910{"text": "def reverse_linked_list(head):\n \"\"\"Reverse a singly linked list.\n Time: O(n), Space: O(1)\n \"\"\"\n prev = None\n current = head\n while current:\n next_node = current.next\n current.next = prev\n prev = current\n current = next_node\n return prev", "lang": "python", "source": "github"}{"text": "def binary_search(arr, target):\n \"\"\"Binary search on a sorted array.\"\"\"\n left, right = 0, len(arr) - 1\n while left <= right:\n mid = (left + right) // 2\n if arr[mid] == target:\n return mid\n elif arr[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n return -1", "lang": "python", "source": "github"}{"text": "class Stack:\n def __init__(self):\n self.items = []\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n if not self.is_empty():\n return self.items.pop()\n raise IndexError('Stack is empty')\n\n def peek(self):\n if not self.is_empty():\n return self.items[-1]\n raise IndexError('Stack is empty')\n\n def is_empty(self):\n return len(self.items) == 0\n\n def size(self):\n return len(self.items)", "lang": "python", "source": "github"}{"text": "function quickSort(arr) {\n if (arr.length <= 1) return arr;\n const pivot = arr[Math.floor(arr.length / 2)];\n const left = arr.filter(x => x < pivot);\n const middle = arr.filter(x => x === pivot);\n const right = arr.filter(x => x > pivot);\n return [...quickSort(left), ...middle, ...quickSort(right)];\n}", "lang": "javascript", "source": "github"}{"text": "async function fetchWithRetry(url, maxRetries = 3) {\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n const response = await fetch(url);\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n return await response.json();\n } catch (err) {\n if (attempt === maxRetries - 1) throw err;\n await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));\n }\n }\n}", "lang": "javascript", "source": "github"}{"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nint binarySearch(const std::vector<int>& arr, int target) {\n int left = 0, right = arr.size() - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (arr[mid] == target) return mid;\n if (arr[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n return -1;\n}", "lang": "cpp", "source": "github"}{"text": "public class Fibonacci {\n // Memoized fibonacci\n private static Map<Integer, Long> memo = new HashMap<>();\n\n public static long fib(int n) {\n if (n <= 1) return n;\n if (memo.containsKey(n)) return memo.get(n);\n long result = fib(n - 1) + fib(n - 2);\n memo.put(n, result);\n return result;\n }\n}", "lang": "java", "source": "github"}{"text": "func mergeSort(arr []int) []int {\n\tif len(arr) <= 1 {\n\t\treturn arr\n\t}\n\tmid := len(arr) / 2\n\tleft := mergeSort(arr[:mid])\n\tright := mergeSort(arr[mid:])\n\treturn merge(left, right)\n}\n\nfunc merge(left, right []int) []int {\n\tresult := make([]int, 0, len(left)+len(right))\n\tfor len(left) > 0 && len(right) > 0 {\n\t\tif left[0] <= right[0] {\n\t\t\tresult = append(result, left[0])\n\t\t\tleft = left[1:]\n\t\t} else {\n\t\t\tresult = append(result, right[0])\n\t\t\tright = right[1:]\n\t\t}\n\t}\n\treturn append(result, append(left, right...)...)\n}", "lang": "go", "source": "github"}{"prompt": "Write a Python decorator that measures execution time", "completion": "import time\nfrom functools import wraps\n\ndef timeit(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = time.perf_counter()\n result = func(*args, **kwargs)\n elapsed = time.perf_counter() - start\n print(f'{func.__name__} took {elapsed:.4f}s')\n return result\n return wrapper\n\n# Usage:\n@timeit\ndef slow_function():\n time.sleep(1)\n return 'done'", "lang": "python"}{"prompt": "Create a TypeScript generic function to remove duplicates from an array", "completion": "function removeDuplicates<T>(arr: T[]): T[] {\n return [...new Set(arr)];\n}\n\n// For objects, use a key extractor:\nfunction removeDuplicatesBy<T, K>(arr: T[], keyFn: (item: T) => K): T[] {\n const seen = new Set<K>();\n return arr.filter(item => {\n const key = keyFn(item);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n// Usage:\nconst nums = removeDuplicates([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4]\nconst users = removeDuplicatesBy(users, u => u.id);", "lang": "typescript"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334"""===================================== Shulker Code — Tokenizer BPE tokenizer optimized for code Developed by @kopeedev / CyeroX=====================================
This tokenizer is specifically designed for programming languages:- Preserves indentation (important for Python!)- Handles special tokens: <code>, </code>, <lang:python>, etc.- Supports 50+ programming languages- BPE (Byte Pair Encoding) vocabulary"""
import osimport jsonimport regex as refrom typing import List, Optional, Dict, Unionfrom pathlib import Path
# ─────────────────────────────────────────────# Special tokens used by Shulker Code# ─────────────────────────────────────────────SPECIAL_TOKENS = { "<pad>": 0, "<bos>": 1, "<eos>": 2, "<unk>": 3, "<sep>": 4, "<mask>": 5, # Code-specific tokens "<code>": 6, "</code>": 7, "<comment>": 8, "</comment>": 9, # Language markers "<lang:py>": 10, "<lang:js>": 11, "<lang:cpp>": 12, "<lang:java>":13, "<lang:ts>": 14, "<lang:go>": 15, "<lang:rs>": 16, "<lang:cs>": 17, # Task markers "<task:gen>": 18, "<task:fix>": 19, "<task:explain>": 20, "<task:optimize>": 21,}
# Language extension to token mappingLANG_TOKENS = { ".py": "<lang:py>", ".js": "<lang:js>", ".ts": "<lang:ts>", ".cpp": "<lang:cpp>", ".cc": "<lang:cpp>", ".java": "<lang:java>", ".go": "<lang:go>", ".rs": "<lang:rs>", ".cs": "<lang:cs>", ".rb": "<lang:rb>", ".php": "<lang:php>",}
class ShulkerTokenizer: """ BPE tokenizer for Shulker Code.
Uses the HuggingFace `tokenizers` library under the hood, but wraps it with code-specific pre/post processing.
For training a tokenizer from scratch: tokenizer = ShulkerTokenizer.train_from_files(files, vocab_size=32000)
For loading a pretrained tokenizer: tokenizer = ShulkerTokenizer.from_pretrained("path/to/tokenizer") """
def __init__(self): self._tokenizer = None self.special_tokens = SPECIAL_TOKENS self.vocab_size = 32000
# Code-aware pre-tokenization regex # Splits on whitespace, but preserves indentation self._code_pattern = re.compile( r"""(?x) \s+ # whitespace (preserved for indentation) | [a-zA-Z_]\w* # identifiers | \d+(?:\.\d+)? # numbers | "(?:[^"\\]|\\.)*" # double-quoted strings | '(?:[^'\\]|\\.)*' # single-quoted strings | `(?:[^`\\]|\\.)*` # backtick strings | (?:\/\/|#)[^\n]* # comments | [+\-*/=<>!&|^~%@]+ # operators | [{}()\[\];:,.] # delimiters | . # fallback """ )
@classmethod def train_from_files( cls, files: List[str], vocab_size: int = 32000, min_frequency: int = 2, save_path: Optional[str] = None, ) -> "ShulkerTokenizer": """ Train a new BPE tokenizer from code files.
Args: files: List of .py, .js, .txt, .jsonl file paths vocab_size: Target vocabulary size min_frequency: Minimum token frequency save_path: Optional directory to save tokenizer
Returns: Trained ShulkerTokenizer instance """ try: from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders, processors except ImportError: raise ImportError("Install tokenizers: pip install tokenizers")
instance = cls()
# Build BPE tokenizer tokenizer = Tokenizer(models.BPE(unk_token="<unk>"))
# Code-aware pre-tokenizer: byte-level BPE tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
# BPE trainer configuration special_token_list = list(SPECIAL_TOKENS.keys()) trainer = trainers.BpeTrainer( vocab_size=vocab_size, min_frequency=min_frequency, special_tokens=special_token_list, initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), show_progress=True, )
# Train on files print(f"🔤 Training BPE tokenizer on {len(files)} files...") tokenizer.train(files, trainer)
# Add byte-level decoder tokenizer.decoder = decoders.ByteLevel()
# Post-processor for BOS/EOS tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)
instance._tokenizer = tokenizer instance.vocab_size = tokenizer.get_vocab_size()
if save_path: instance.save(save_path) print(f"✅ Tokenizer saved to {save_path}")
print(f"✅ Tokenizer trained: {instance.vocab_size:,} tokens") return instance
@classmethod def from_pretrained(cls, path: str) -> "ShulkerTokenizer": """Load a saved tokenizer from disk.""" try: from tokenizers import Tokenizer except ImportError: raise ImportError("Install tokenizers: pip install tokenizers")
instance = cls() tokenizer_path = os.path.join(path, "tokenizer.json") instance._tokenizer = Tokenizer.from_file(tokenizer_path) instance.vocab_size = instance._tokenizer.get_vocab_size()
# Load vocab size override if present config_path = os.path.join(path, "tokenizer_config.json") if os.path.exists(config_path): with open(config_path) as f: config = json.load(f) instance.vocab_size = config.get("vocab_size", instance.vocab_size)
print(f"✅ Tokenizer loaded from {path} ({instance.vocab_size:,} tokens)") return instance
@classmethod def from_hf_pretrained(cls, model_name: str = "microsoft/codebert-base") -> "ShulkerTokenizer": """ Bootstrap from a HuggingFace pretrained tokenizer. Useful for quick setup without training from scratch. """ try: from transformers import AutoTokenizer except ImportError: raise ImportError("Install transformers: pip install transformers")
instance = cls() hf_tokenizer = AutoTokenizer.from_pretrained(model_name)
# Wrap HF tokenizer with our interface instance._hf_tokenizer = hf_tokenizer instance._use_hf = True instance.vocab_size = hf_tokenizer.vocab_size
print(f"✅ Using HuggingFace tokenizer: {model_name} ({instance.vocab_size:,} tokens)") return instance
def encode( self, text: str, add_special_tokens: bool = True, max_length: Optional[int] = None, lang: Optional[str] = None, ) -> List[int]: """ Encode text to token IDs.
Args: text: Input text/code add_special_tokens: Wrap with <bos>/<eos> max_length: Truncate to this length lang: Optional language hint (e.g. "python", "javascript")
Returns: List of integer token IDs """ if hasattr(self, "_use_hf") and self._use_hf: result = self._hf_tokenizer.encode( text, add_special_tokens=add_special_tokens, max_length=max_length, truncation=max_length is not None, ) return result
if self._tokenizer is None: raise RuntimeError("Tokenizer not initialized. Call train_from_files() or from_pretrained() first.")
encoding = self._tokenizer.encode(text) ids = encoding.ids
if add_special_tokens: ids = [self.special_tokens["<bos>"]] + ids + [self.special_tokens["<eos>"]]
if max_length: ids = ids[:max_length]
return ids
def decode(self, ids: List[int], skip_special_tokens: bool = True) -> str: """Decode token IDs back to text.""" if hasattr(self, "_use_hf") and self._use_hf: return self._hf_tokenizer.decode(ids, skip_special_tokens=skip_special_tokens)
if self._tokenizer is None: raise RuntimeError("Tokenizer not initialized.")
if skip_special_tokens: special_ids = set(self.special_tokens.values()) ids = [i for i in ids if i not in special_ids]
return self._tokenizer.decode(ids)
def encode_code( self, code: str, language: str = "python", task: str = "gen", max_length: Optional[int] = None, ) -> List[int]: """ Encode code with language and task context tokens. Example output: [<bos>, <task:gen>, <lang:py>, ...code tokens..., <eos>] """ lang_map = { "python": "<lang:py>", "py": "<lang:py>", "javascript": "<lang:js>", "js": "<lang:js>", "typescript": "<lang:ts>", "ts": "<lang:ts>", "cpp": "<lang:cpp>", "c++": "<lang:cpp>", "java": "<lang:java>", "go": "<lang:go>", "golang": "<lang:go>", "rust": "<lang:rs>", "rs": "<lang:rs>", } task_map = { "gen": "<task:gen>", "generate": "<task:gen>", "fix": "<task:fix>", "debug": "<task:fix>", "explain": "<task:explain>", "optimize": "<task:optimize>", "refactor": "<task:optimize>", }
lang_token = lang_map.get(language.lower(), "<lang:py>") task_token = task_map.get(task.lower(), "<task:gen>")
prefix = f"{task_token} {lang_token} " full_text = prefix + code
return self.encode(full_text, add_special_tokens=True, max_length=max_length)
def save(self, path: str): """Save tokenizer to directory.""" os.makedirs(path, exist_ok=True)
if hasattr(self, "_use_hf") and self._use_hf: self._hf_tokenizer.save_pretrained(path) elif self._tokenizer is not None: self._tokenizer.save(os.path.join(path, "tokenizer.json"))
# Save config with open(os.path.join(path, "tokenizer_config.json"), "w") as f: json.dump({ "vocab_size": self.vocab_size, "special_tokens": self.special_tokens, "model_type": "shulker_bpe", }, f, indent=2)
@property def pad_token_id(self) -> int: return self.special_tokens["<pad>"]
@property def bos_token_id(self) -> int: return self.special_tokens["<bos>"]
@property def eos_token_id(self) -> int: return self.special_tokens["<eos>"]
def __len__(self) -> int: return self.vocab_sizedata/__init__.pyAdded+4
data/dataset.pyAdded+295
data/sample_dataset.jsonlAdded+10
data/tokenizer.pyAdded+334