199 lines
6.4 KiB
Python
199 lines
6.4 KiB
Python
import dataclasses
|
|
from typing import List, Dict, Any
|
|
try:
|
|
import yaml
|
|
except ImportError: # pyyaml не установлен — Config.load/save недоступны
|
|
yaml = None
|
|
from enum import StrEnum
|
|
|
|
class IP:
|
|
ip: str
|
|
def __init__(self, oct1, oct2, oct3, oct4): self.ip = f"{oct1}.{oct2}.{oct3}.{oct4}"
|
|
def __repr__(self) -> str: return self.ip
|
|
|
|
class UpdatePolicy(StrEnum):
|
|
NONE = "none"
|
|
NOTIFY = "notify"
|
|
AUTO = "auto"
|
|
|
|
class LogLevel(StrEnum):
|
|
DEBUG = "debug"
|
|
INFO = "info"
|
|
WARN = "warn"
|
|
ERROR = "error"
|
|
|
|
class BackendType(StrEnum):
|
|
CPU = "cpu"
|
|
VULKAN = "vulkan"
|
|
|
|
class ModelOllama:
|
|
name: str = ""
|
|
path: str = ""
|
|
|
|
@dataclasses.dataclass
|
|
class ProjectConfig:
|
|
name: str = "Xenith"
|
|
version: str = "version.txt"
|
|
|
|
@dataclasses.dataclass
|
|
class UpdateConfig:
|
|
enable: bool = True
|
|
policy: UpdatePolicy = UpdatePolicy.NOTIFY
|
|
repo: str = "https://git.bipfr.ru/BIPfR/Xenith"
|
|
branch: str = "master"
|
|
version_path: str = "version.txt"
|
|
archive_pattern: str = "https://git.bipfr.ru/BIPfR/Xenith/archive/{version}.zip"
|
|
api_base: str = "https://git.bipfr.ru/api/v1/repos/BIPfR/Xenith"
|
|
install_dir: str = ""
|
|
backup_dir: str = "tmp/backup"
|
|
check_on_start: bool = False
|
|
allow_prerelease: bool = False
|
|
timeout_sec: int = 15
|
|
verify_tls: bool = True
|
|
keep: List[str] = dataclasses.field(default_factory=lambda: [
|
|
"models", "config.yaml", "tmp", "logs",
|
|
"dataset.conf.json", "ollama.conf"
|
|
])
|
|
|
|
@dataclasses.dataclass
|
|
class ServerConfig:
|
|
host: IP = IP(127,0,0,1)
|
|
port: int = 11434
|
|
default_model: str = ""
|
|
models_dir: str = "models"
|
|
scan_models: bool = True
|
|
gen_threads: int = 1
|
|
max_body_kb: int = 65536
|
|
request_timeout_sec: int = 600
|
|
verbose: bool = False
|
|
cors: bool = True
|
|
api_key: str = ""
|
|
models: List[ModelOllama] = dataclasses.field(default_factory=list)
|
|
|
|
@dataclasses.dataclass
|
|
class UiConfig:
|
|
progress: bool = True
|
|
color: bool = True
|
|
bar_width: int = 32
|
|
eta: bool = True
|
|
sparkline: bool = True
|
|
spinner: bool = True
|
|
timestamps: bool = False
|
|
ascii_only: bool = False
|
|
|
|
@dataclasses.dataclass
|
|
class LogConfig:
|
|
level: LogLevel = LogLevel.INFO
|
|
file: str = ""
|
|
to_stderr: bool = True
|
|
overwrite: bool = False
|
|
|
|
@dataclasses.dataclass
|
|
class RuntimeConfig:
|
|
backend: BackendType = BackendType.CPU
|
|
threads: int = 0
|
|
threads_cap: int = 16
|
|
seed: int = 1337
|
|
models_dir: str = "models"
|
|
tmp_dir: str = "tmp"
|
|
|
|
@dataclasses.dataclass
|
|
class VulkanConfig:
|
|
enabled: bool = True
|
|
device_index: int = -1
|
|
validation_layers: bool = False
|
|
min_gemm_flops: int = 262144
|
|
workgroup_size: int = 64
|
|
staging_mb: int = 256
|
|
persistent_buffers: bool = True
|
|
allow_integrated: bool = True
|
|
fp16: bool = False
|
|
|
|
@dataclasses.dataclass
|
|
class TokenizerConfig:
|
|
min_vocab: int = 16
|
|
|
|
@dataclasses.dataclass
|
|
class CheckpointConfig:
|
|
atomic_write: bool = True
|
|
fsync: bool = False
|
|
save_optimizer: bool = True
|
|
compress: bool = False
|
|
|
|
@dataclasses.dataclass
|
|
class Config:
|
|
project: ProjectConfig = dataclasses.field(default_factory=ProjectConfig)
|
|
update: UpdateConfig = dataclasses.field(default_factory=UpdateConfig)
|
|
server: ServerConfig = dataclasses.field(default_factory=ServerConfig)
|
|
ui: UiConfig = dataclasses.field(default_factory=UiConfig)
|
|
log: LogConfig = dataclasses.field(default_factory=LogConfig)
|
|
runtime: RuntimeConfig = dataclasses.field(default_factory=RuntimeConfig)
|
|
vulkan: VulkanConfig = dataclasses.field(default_factory=VulkanConfig)
|
|
tokenizer: TokenizerConfig = dataclasses.field(default_factory=TokenizerConfig)
|
|
checkpoint: CheckpointConfig = dataclasses.field(default_factory=CheckpointConfig)
|
|
@staticmethod
|
|
def _deep_merge(base: dict, override: dict) -> dict:
|
|
result = base.copy()
|
|
for key, value in override.items():
|
|
if (
|
|
key in result
|
|
and isinstance(result[key], dict)
|
|
and isinstance(value, dict)
|
|
):
|
|
result[key] = Config._deep_merge(result[key], value)
|
|
else:
|
|
result[key] = value
|
|
return result
|
|
@classmethod
|
|
def load(cls, path: str = "./config.yaml") -> "Config":
|
|
if yaml is None:
|
|
raise RuntimeError("нужен pyyaml: pip install pyyaml")
|
|
defaults_dict = dataclasses.asdict(cls())
|
|
file_data: dict = {}
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
loaded = yaml.safe_load(f)
|
|
if isinstance(loaded, dict):
|
|
file_data = loaded
|
|
merged = cls._deep_merge(defaults_dict, file_data)
|
|
return cls.from_dict(merged)
|
|
@classmethod
|
|
def from_dict(cls, data: dict) -> "Config":
|
|
mapping = {
|
|
"project": ProjectConfig,
|
|
"update": UpdateConfig,
|
|
"server": ServerConfig,
|
|
"ui": UiConfig,
|
|
"log": LogConfig,
|
|
"runtime": RuntimeConfig,
|
|
"vulkan": VulkanConfig,
|
|
"tokenizer": TokenizerConfig,
|
|
"checkpoint": CheckpointConfig,
|
|
}
|
|
kwargs: Dict[str, Any] = {}
|
|
for field_name, sub_cls in mapping.items():
|
|
sub_data = data.get(field_name, {})
|
|
if isinstance(sub_data, dict):
|
|
if field_name == "defaults":
|
|
kwargs[field_name] = cls._from_dict_defaults(sub_data)
|
|
elif hasattr(sub_cls, "__dataclass_fields__"):
|
|
kwargs[field_name] = sub_cls(**sub_data)
|
|
else:
|
|
kwargs[field_name] = sub_data
|
|
else:
|
|
kwargs[field_name] = sub_cls()
|
|
return cls(**kwargs)
|
|
def save(self, path: str = "./config.yaml") -> None:
|
|
if yaml is None:
|
|
raise RuntimeError("нужен pyyaml: pip install pyyaml")
|
|
data = dataclasses.asdict(self)
|
|
def _convert_enums(obj):
|
|
if isinstance(obj, StrEnum):
|
|
return obj.value
|
|
if isinstance(obj, dict):
|
|
return {k: _convert_enums(v) for k, v in obj.items()}
|
|
if isinstance(obj, list):
|
|
return [_convert_enums(i) for i in obj]
|
|
return obj
|
|
data = _convert_enums(data)
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
yaml.dump(data, f, allow_unicode=True, sort_keys=False, default_flow_style=False) |