File size: 2,505 Bytes
91ac3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from __future__ import annotations

from pathlib import Path
from typing import Any

import yaml
from transformers import LlamaConfig


def load_yaml(path: str | Path) -> dict[str, Any]:
    config_path = Path(path)
    with config_path.open("r", encoding="utf-8") as handle:
        data = yaml.safe_load(handle)
    if not isinstance(data, dict):
        raise ValueError(f"YAML root must be a mapping: {config_path}")
    return data


def _positive_int(value: Any, name: str) -> int:
    if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
        raise ValueError(f"{name} must be a positive integer, got {value!r}")
    return value


def build_llama_config(
    model_data: dict[str, Any],
    *,
    tokenizer_vocab_size: int | None = None,
) -> tuple[LlamaConfig, int | None]:
    """Validate a model mapping and return a Hugging Face LlamaConfig."""
    if "model" in model_data:
        model_data = model_data["model"]
    if not isinstance(model_data, dict):
        raise ValueError("model configuration must be a mapping")

    values = dict(model_data)
    expected_parameters = values.pop("expected_parameters", None)

    required = (
        "vocab_size",
        "hidden_size",
        "intermediate_size",
        "num_hidden_layers",
        "num_attention_heads",
        "num_key_value_heads",
        "max_position_embeddings",
    )
    for name in required:
        values[name] = _positive_int(values.get(name), name)

    if values["hidden_size"] % values["num_attention_heads"] != 0:
        raise ValueError("hidden_size must be divisible by num_attention_heads")
    if values["num_attention_heads"] % values["num_key_value_heads"] != 0:
        raise ValueError(
            "num_attention_heads must be divisible by num_key_value_heads"
        )
    if tokenizer_vocab_size is not None and values["vocab_size"] != tokenizer_vocab_size:
        raise ValueError(
            "Tokenizer/model vocabulary mismatch: "
            f"tokenizer={tokenizer_vocab_size}, model={values['vocab_size']}"
        )

    config = LlamaConfig(**values)
    return config, expected_parameters


def count_unique_parameters(model: Any) -> int:
    """Count parameters without double-counting tied tensors."""
    seen: set[int] = set()
    total = 0
    for parameter in model.parameters():
        pointer = parameter.untyped_storage().data_ptr()
        if pointer not in seen:
            seen.add(pointer)
            total += parameter.numel()
    return total