s0duku's picture
Add generic native parser fallback and sample recovery
804ecef verified
Raw History Blame Contribute Delete
19.3 kB
"""End-to-end DeepSeek-style repository training sample construction."""
from __future__ import annotations
import hashlib
import math
from collections import OrderedDict, deque
from typing import Callable
from .content import normalized_path, training_content
from .graph import dependency_components
from .model import (
BEGIN_FILE,
BEGIN_FILE_NAME,
BEGIN_REPO_NAME,
END_FILE,
END_FILE_NAME,
END_REPO_NAME,
BuildConfig,
Sample,
SampleFile,
)
from .repo import Repo, RepoFile, RepoInfo, scan
from .tokenizer import load_tokenizer
TokenCounter = Callable[[str], int]
class _Counter:
def __init__(self, tokenizer=None, utf8_bytes_per_token: float = 3.0):
self.tokenizer = tokenizer
self.utf8_bytes_per_token = utf8_bytes_per_token
self.mode = (f"utf8_estimate_{utf8_bytes_per_token:g}bytes_per_token"
if tokenizer is None else "tokens")
self._cache: OrderedDict[str, int] = OrderedDict()
def __call__(self, text: str) -> int:
if text in self._cache:
self._cache.move_to_end(text)
return self._cache[text]
if self.tokenizer is None:
byte_count = len(text.encode("utf-8"))
value = math.ceil(byte_count / self.utf8_bytes_per_token)
else:
encode = getattr(self.tokenizer, "encode", None)
if encode is not None:
try:
value = len(encode(text, add_special_tokens=False))
except TypeError:
try:
value = len(encode(text, disallowed_special=()))
except TypeError:
value = len(encode(text))
elif callable(self.tokenizer):
result = self.tokenizer(text)
value = result if isinstance(result, int) else len(result)
else:
raise TypeError("tokenizer must be callable or provide encode()")
self._cache[text] = value
if len(self._cache) > 128:
self._cache.popitem(last=False)
return value
def build_samples(repo: Repo, *, config: BuildConfig | None = None, tokenizer=None,
info: RepoInfo | None = None,
use_treesitter: bool = True) -> tuple[Sample, ...]:
"""Analyze ``repo`` and return deterministic, budgeted training samples."""
config = config or BuildConfig()
tokenizer = tokenizer or load_tokenizer()
counter = _Counter(tokenizer, config.utf8_bytes_per_token)
repo_files = tuple(repo.iter_files())
snapshot = Repo(repo.repo_id, repo.revision_id, repo_files)
info = info or scan(
snapshot, include_weak=config.include_weak_edges,
use_treesitter=use_treesitter,
)
files = {normalized_path(file.path): file for file in repo_files}
if len(files) != len(repo_files):
raise ValueError("Repo contains duplicate normalized file paths")
if set(files) != {file.path for file in info.files}:
raise ValueError("RepoInfo does not describe the supplied Repo snapshot")
rendered = {
path: training_content(file, config)
for path, file in files.items()
}
samples = _dependency_samples(snapshot, info, rendered, config, counter)
if config.target_context:
samples.extend(_target_context_samples(snapshot, info, rendered, config, counter, samples))
return tuple(samples)
def _repository_header(repo: Repo) -> str:
return f"{BEGIN_REPO_NAME}{repo.repo_id}{END_REPO_NAME}\n"
def _file_block(path: str, content: str, policy: str, role: str, *, part: int = 1,
parts: int = 1) -> str:
suffix = f" (part {part}/{parts})" if parts > 1 else ""
lines = [f"{BEGIN_FILE_NAME}{path}{suffix}{END_FILE_NAME}", BEGIN_FILE]
if content:
lines.append(content.rstrip())
lines.append(END_FILE)
return "\n".join(lines) + "\n"
def _chunks(path: str, content: str, policy: str, role: str, language: str | None,
budget: int, counter: TokenCounter) -> tuple[str, ...]:
if not content:
return ("",)
# Avoid sending multi-megabyte source files through the tokenizer several
# times. Besides being quadratic in the old binary search, concurrent huge
# encodes can exhaust system memory. Normal files still take the fast path.
max_candidate_chars = 262_144
if (len(content) <= max_candidate_chars
and counter(_file_block(path, content, policy, role)) <= budget):
return (content,)
# Splitting adds a part=i/n descriptor. Reserve its worst practical width
# while finding boundaries so the final rendered blocks remain in budget.
def split_block(value: str) -> str:
return _file_block(path, value, policy, role, part=999_999, parts=999_999)
units: list[str] = []
unit_chars = 16_384
for line in content.splitlines(keepends=True):
units.extend(line[start:start + unit_chars] for start in range(0, len(line), unit_chars))
if not units and content:
units = [content]
def exact_split(parts: list[str]) -> list[str]:
chunks: list[str] = []
current = ""
for unit in parts:
candidate = current + unit
if (len(candidate) <= max_candidate_chars
and counter(split_block(candidate)) <= budget):
current = candidate
continue
if current:
chunks.append(current)
current = ""
while unit:
if counter(split_block(unit)) <= budget:
current = unit
break
lo, hi, chars = 1, len(unit), 0
while lo <= hi:
middle = (lo + hi) // 2
if counter(split_block(unit[:middle])) <= budget:
chars = middle
lo = middle + 1
else:
hi = middle - 1
if not chars:
raise ValueError(f"max_tokens is too small for file metadata: {path}")
chunks.append(unit[:chars])
unit = unit[chars:]
if current:
chunks.append(current)
return chunks
chunks: list[str] = []
start = 0
while start < len(units):
# Find the largest exact unit prefix that fits. This preserves the old
# greedy boundaries while replacing O(units) repeated encodes with
# O(log units) encodes per output chunk.
low, high, best = 1, len(units) - start, 0
while low <= high:
middle = (low + high) // 2
candidate = "".join(units[start:start + middle])
if (len(candidate) <= max_candidate_chars
and counter(split_block(candidate)) <= budget):
best = middle
low = middle + 1
else:
high = middle - 1
if best:
chunks.append("".join(units[start:start + best]))
start += best
continue
chunks.extend(exact_split([units[start]]))
start += 1
return tuple(chunks)
def _dependency_samples(repo, info, rendered, config, counter) -> list[Sample]:
samples: list[Sample] = []
language_by_path = {file.path: file.language for file in info.files}
components = dependency_components(info)
linked = [component for component in components if len(component) > 1]
isolated_set = {component[0] for component in components if len(component) == 1}
isolated = tuple(path for path in info.topological_order if path in isolated_set)
groups = linked + ([isolated] if isolated else [])
header = _repository_header(repo)
header_tokens = counter(header)
file_budget = config.max_tokens - header_tokens
if file_budget < 1:
raise ValueError("max_tokens is too small for repository metadata")
if config.max_file_tokens is not None:
file_budget = min(file_budget, config.max_file_tokens)
for component_index, component in enumerate(groups):
entries: list[tuple[str, str, str, str, str | None, int, int]] = []
for path in component:
content, policy, role = rendered[path]
language = language_by_path[path]
parts = _chunks(path, content, policy, role, language, file_budget, counter)
entries.extend((path, part, policy, role, language, index, len(parts))
for index, part in enumerate(parts, 1))
pack: list[tuple[str, str, str, str, str | None, int, int]] = []
pack_text = ""
used = 0
def flush() -> None:
nonlocal pack, pack_text, used
text = header + pack_text
token_count = counter(text)
if token_count > config.max_tokens:
raise ValueError(
f"dependency sample exceeds max_tokens for {repo.repo_id}: {token_count}"
)
sample = _make_dependency(
repo, info, samples, pack, component_index, counter,
text=text, token_count=token_count,
)
if sample.token_count >= config.min_tokens:
samples.append(sample)
pack, pack_text, used = [], "", 0
for entry in entries:
block = _file_block(entry[0], entry[1], entry[2], entry[3],
part=entry[5], parts=entry[6])
cost = counter(block)
if pack and header_tokens + used + cost > config.max_tokens:
flush()
pack.append(entry)
pack_text += block
used += cost
if header_tokens + cost > config.max_tokens:
raise ValueError(f"file block exceeds max_tokens: {entry[0]}")
if pack:
flush()
return samples
def _make_dependency(repo, info, existing, entries, component_index, counter, *,
text: str | None = None, token_count: int | None = None) -> Sample:
text = text if text is not None else _repository_header(repo) + "".join(
_file_block(path, content, policy, role, part=part, parts=parts)
for path, content, policy, role, language, part, parts in entries
)
language_by_path = {file.path: file.language for file in info.files}
provenance = tuple(SampleFile(
path=path, relation="component", content_policy=policy,
role=role, language=language_by_path[path], bytes=len(content.encode("utf-8")),
part=part, parts=parts,
) for path, content, policy, role, language, part, parts in entries)
return Sample(
sample_id=_sample_id(repo, "dependency", len(existing), tuple(x[0] for x in entries)),
repo_id=repo.repo_id, revision_id=repo.revision_id, kind="dependency", text=text,
files=provenance, token_count=token_count if token_count is not None else counter(text),
metadata={"component": component_index, "counter": counter.mode},
)
def _target_candidates(repo, info, rendered, config) -> tuple[str, ...]:
"""Choose stable, broadly distributed source targets without graph ranking."""
roles = {path: value[2] for path, value in rendered.items()}
language = {file.path: file.language for file in info.files}
candidates = [
path for path in info.topological_order
if roles.get(path) == "source"
and language.get(path)
and rendered[path][0]
and rendered[path][1] != "metadata_only"
]
if len(candidates) <= config.max_targets_per_repo:
return tuple(candidates)
ranked = sorted(
candidates,
key=lambda path: hashlib.sha1(
f"{repo.repo_id}\0{repo.revision_id}\0target\0{path}".encode()
).digest(),
)
selected = set(ranked[:config.max_targets_per_repo])
return tuple(path for path in info.topological_order if path in selected)
def _target_dependencies(info, target: str, max_depth: int) -> tuple[str, ...]:
"""Return transitive dependencies, preserving dependency-first presentation."""
dependencies: dict[str, set[str]] = {}
for edge in info.edges:
if edge.status == "resolved" and edge.source != edge.target:
dependencies.setdefault(edge.source, set()).add(edge.target)
distance = {target: 0}
queue = deque([target])
while queue:
source = queue.popleft()
depth = distance[source]
if depth >= max_depth:
continue
for dependency in sorted(dependencies.get(source, ())):
if dependency not in distance:
distance[dependency] = depth + 1
queue.append(dependency)
position = {path: index for index, path in enumerate(info.topological_order)}
return tuple(sorted(
(path for path in distance if path != target),
key=lambda path: (distance[path], position[path]),
))
def _direct_dependencies(info, target: str) -> tuple[str, ...]:
position = {path: index for index, path in enumerate(info.topological_order)}
return tuple(sorted(
{
edge.target for edge in info.edges
if edge.status == "resolved" and edge.source == target and edge.target != target
},
key=position.__getitem__,
))
def _target_context_samples(repo, info, rendered, config, counter, existing_samples=()) -> list[Sample]:
samples: list[Sample] = []
existing_texts = {sample.text for sample in existing_samples}
language = {file.path: file.language for file in info.files}
roles = {path: value[2] for path, value in rendered.items()}
position = {path: index for index, path in enumerate(info.topological_order)}
by_directory: dict[str, list[str]] = {}
for path in info.topological_order:
parent = path.rsplit("/", 1)[0] if "/" in path else ""
by_directory.setdefault(parent, []).append(path)
for target in _target_candidates(repo, info, rendered, config):
dependency_paths = list(_target_dependencies(info, target, config.max_dependency_depth))
target_content, target_policy, target_role = rendered[target]
budget = config.max_tokens - counter(_repository_header(repo))
if budget < 1:
continue
if config.max_file_tokens is not None:
budget = min(budget, config.max_file_tokens)
target_parts = _chunks(target, target_content, target_policy, target_role,
language.get(target), budget, counter)
target_blocks = [
_file_block(target, part, target_policy, target_role, part=index, parts=len(target_parts))
for index, part in enumerate(target_parts, 1)
]
for target_index, target_block in enumerate(target_blocks, 1):
entries: list[tuple[str, str, str, str, str | None, int, int]] = []
used = counter(target_block)
selected: list[str] = []
# Direct dependencies and then nearer transitive dependencies are considered first.
for path in dependency_paths:
content, policy, role = rendered[path]
if policy == "metadata_only":
continue
parts = _chunks(path, content, policy, role, language.get(path), budget, counter)
if len(parts) != 1:
continue
block = _file_block(path, parts[0], policy, role)
if used + counter(block) <= budget:
selected.append(path)
used += counter(block)
dependency_selected = set(selected)
# Small local documentation/build context gets the remaining space.
target_dir = target.rsplit("/", 1)[0] if "/" in target else ""
context_candidates = [
path for path in by_directory.get(target_dir, ())
if path != target and roles.get(path) in {"documentation", "manifest", "build"}
]
context_candidates += [
path for path in ("README.md", "README.rst", "pyproject.toml", "package.json", "Cargo.toml")
if path in rendered and path != target and path not in context_candidates
]
for path in context_candidates:
if path in selected:
continue
content, policy, role = rendered[path]
block = _file_block(path, content, policy, role)
if counter(block) <= 1024 and used + counter(block) <= budget:
selected.append(path)
used += counter(block)
selected.sort(key=position.__getitem__)
for path in selected:
content, policy, role = rendered[path]
entries.append((path, content, policy, role, language.get(path), 1, 1))
target_part = target_parts[target_index - 1]
# A target-only document duplicates the ordinary dependency sample
# and adds no repository context, so do not emit it.
if not selected:
continue
entries.append((target, target_part, target_policy, target_role,
language.get(target), target_index, len(target_parts)))
text = _repository_header(repo) + "".join(
_file_block(path, content, policy, role, part=part, parts=parts)
for path, content, policy, role, _, part, parts in entries
)
if counter(text) > config.max_tokens:
continue
if text in existing_texts:
continue
provenance = tuple(SampleFile(
path=path,
relation=("target" if path == target else
"dependency" if path in dependency_selected else "repository_context"),
content_policy=policy, role=role, language=language.get(path),
bytes=len(content.encode("utf-8")), part=part, parts=parts,
) for path, content, policy, role, _, part, parts in entries)
samples.append(Sample(
sample_id=_sample_id(repo, "target_context", len(samples),
tuple(path for path, *_ in entries)),
repo_id=repo.repo_id, revision_id=repo.revision_id,
kind="target_context", text=text, files=provenance,
token_count=counter(text), metadata={
"target_path": target,
"direct_dependency_paths": _direct_dependencies(info, target),
"dependency_depth": config.max_dependency_depth,
"dependency_paths": tuple(path for path in selected if path in dependency_selected),
"repository_context_paths": tuple(path for path in selected if path not in dependency_selected),
"counter": counter.mode,
},
))
existing_texts.add(text)
return samples
def _sample_id(repo: Repo, kind: str, index: int, paths: tuple[str, ...]) -> str:
value = "\0".join((repo.repo_id, repo.revision_id, kind, str(index), *paths))
return hashlib.sha1(value.encode()).hexdigest()