rigma 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rigma/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
rigma/cli.py ADDED
@@ -0,0 +1,99 @@
1
+ from __future__ import annotations
2
+
3
+ import platform
4
+
5
+ import typer
6
+
7
+ from .probe import probe_hardware
8
+ from .registry import Registry
9
+ from .resolve import resolve
10
+
11
+ app = typer.Typer(no_args_is_help=True, add_completion=False)
12
+
13
+
14
+ def _profile(reg: Registry):
15
+ return probe_hardware(reg.gpus)
16
+
17
+
18
+ @app.command()
19
+ def doctor():
20
+ """Print detected hardware and registry status."""
21
+ reg = Registry.load()
22
+ p = _profile(reg)
23
+ typer.echo(p.model_dump_json(indent=2))
24
+ typer.echo(f"fingerprint: {p.fingerprint}")
25
+ typer.echo(f"registry: {len(reg.models)} models, {len(reg.combos)} combos")
26
+
27
+
28
+ @app.command()
29
+ def plan(use_case: str = typer.Option("general", "--use-case"),
30
+ model: str = typer.Option(None, "--model"),
31
+ explain: bool = typer.Option(False, "--explain")):
32
+ """Show what `rigma up` would run, and why."""
33
+ reg = Registry.load()
34
+ rp = resolve(_profile(reg), reg, use_case=use_case, model_override=model)
35
+ typer.echo(f"model: {rp.model_slug} ({rp.gguf.quant}, "
36
+ f"{rp.gguf.bytes / 2**30:.1f} GB)")
37
+ typer.echo(f"backend: {rp.backend} origin: {rp.origin}")
38
+ typer.echo(f"flags: {rp.flags.model_dump()}")
39
+ if explain:
40
+ for line in rp.explain:
41
+ typer.echo(f" {line}")
42
+
43
+
44
+ @app.command()
45
+ def models():
46
+ """List registry models and whether they fit this machine."""
47
+ reg = Registry.load()
48
+ p = _profile(reg)
49
+ for slug, spec in sorted(reg.models.items()):
50
+ try:
51
+ rp = resolve(p, reg, model_override=slug)
52
+ fit = (f"fits as {rp.gguf.quant} (n_cpu_moe={rp.flags.n_cpu_moe})"
53
+ if rp.model_slug == slug else "does not fit")
54
+ except Exception:
55
+ fit = "does not fit"
56
+ typer.echo(f"{slug:24} {spec.kind:5} {fit}")
57
+
58
+
59
+ @app.command()
60
+ def up(use_case: str = typer.Option("general", "--use-case"),
61
+ model: str = typer.Option(None, "--model"),
62
+ yes: bool = typer.Option(False, "--yes", "-y"),
63
+ dry_run: bool = typer.Option(False, "--dry-run"),
64
+ port: int = typer.Option(11500, "--port"),
65
+ turbo: bool = typer.Option(False, "--turbo",
66
+ help="Max-speed download (may saturate your connection)")):
67
+ """Probe -> resolve -> download -> serve."""
68
+ import os
69
+
70
+ from . import runtime # local import: keeps --dry-run path light
71
+
72
+ if turbo:
73
+ os.environ["HF_HUB_DISABLE_XET"] = "0"
74
+ os.environ["HF_XET_NUM_CONCURRENT_RANGE_GETS"] = "16"
75
+
76
+ reg = Registry.load()
77
+ p = _profile(reg)
78
+ rp = resolve(p, reg, use_case=use_case, model_override=model)
79
+ os_name = {"Windows": "windows", "Linux": "linux",
80
+ "Darwin": "darwin"}[platform.system()]
81
+ argv_preview = rp.server_args("<model>", port)
82
+ typer.echo(f"plan: {rp.model_slug} {rp.gguf.quant} on {rp.backend} "
83
+ f"({rp.origin})")
84
+ typer.echo("argv: llama-server " + " ".join(argv_preview))
85
+ if dry_run:
86
+ raise typer.Exit(0)
87
+ if not yes:
88
+ typer.confirm(
89
+ f"download engine + model ({rp.gguf.bytes / 2**30:.1f} GB)?", abort=True)
90
+ exe = runtime.ensure_engine(rp.backend, os_name)
91
+ model_path = runtime.ensure_model(rp.gguf)
92
+ typer.echo("starting llama-server (first load can take minutes)...")
93
+ sp = runtime.launch_server(exe, rp, model_path, port=port)
94
+ typer.echo(f"ready: OpenAI-compatible endpoint at {sp.url}/v1")
95
+ typer.echo("Ctrl+C to stop.")
96
+ try:
97
+ sp.proc.wait()
98
+ except KeyboardInterrupt:
99
+ sp.stop()
@@ -0,0 +1,15 @@
1
+ {
2
+ "version": "b9867",
3
+ "url_base": "https://github.com/ggml-org/llama.cpp/releases/download/b9867/",
4
+ "assets": {
5
+ "windows/vulkan": "llama-b9867-bin-win-vulkan-x64.zip",
6
+ "windows/cuda": "llama-b9867-bin-win-cuda-12.4-x64.zip",
7
+ "windows/rocm": "llama-b9867-bin-win-hip-radeon-x64.zip",
8
+ "windows/cpu": "llama-b9867-bin-win-cpu-x64.zip",
9
+ "linux/vulkan": "llama-b9867-bin-ubuntu-vulkan-x64.tar.gz",
10
+ "linux/cpu": "llama-b9867-bin-ubuntu-x64.tar.gz"
11
+ },
12
+ "extra_assets": {
13
+ "windows/cuda": ["cudart-llama-bin-win-cuda-12.4-x64.zip"]
14
+ }
15
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "model": "qwen3.6-35b-a3b", "quant": "UD-Q3_K_XL", "backend": "vulkan",
3
+ "flags": {"ctx": 16384, "ngl": 99, "n_cpu_moe": 12, "flash_attn": true,
4
+ "cache_type_k": "q8_0", "cache_type_v": "q8_0"},
5
+ "notes": "Conservative class fallback for unknown 16GB cards with 16GB RAM; unverified.",
6
+ "sources": ["https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF"]
7
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "model": "qwen3.6-35b-a3b", "quant": "UD-Q3_K_XL", "backend": "vulkan",
3
+ "flags": {"ctx": 32768, "ngl": 99, "n_cpu_moe": 10, "flash_attn": true,
4
+ "cache_type_k": "q8_0", "cache_type_v": "q8_0"},
5
+ "budget": {"vram_mb": 15200, "ram_mb": 5500},
6
+ "expected": {"tg_tps": [40, 60], "pp_tps": [400, 700]},
7
+ "verified": {"by": "IxMxAMAR", "date": "2026-07-06", "llamacpp": "b9867",
8
+ "measured": {"tg_tps": 57.1, "pp_tps": 689, "prompt_tokens": 4020}},
9
+ "notes": "Vulkan ~20-29% faster than ROCm on RDNA4; TurboQuant forks excluded (crash >65K ctx on this card).",
10
+ "sources": ["https://digtvbg.com/blog/llama-server-vulkan-rdna4-vllm-rocm-benchmark/",
11
+ "https://github.com/ggml-org/llama.cpp/issues/23098"]
12
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "model": "qwen3.6-35b-a3b", "quant": "UD-Q3_K_XL", "backend": "vulkan",
3
+ "flags": {"ctx": 16384, "ngl": 99, "n_cpu_moe": 8, "flash_attn": true,
4
+ "cache_type_k": "q8_0", "cache_type_v": "q8_0"},
5
+ "budget": {"vram_mb": 15200, "ram_mb": 4500},
6
+ "expected": {"tg_tps": [22, 32], "pp_tps": [150, 400]},
7
+ "verified": {"by": "IxMxAMAR", "date": "2026-07-03"},
8
+ "notes": "Smaller ctx than the coding combo keeps more experts on-GPU for faster general chat.",
9
+ "sources": ["https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF"]
10
+ }
@@ -0,0 +1,16 @@
1
+ [
2
+ {"match": "RX 9070", "vendor": "amd", "arch": "rdna4",
3
+ "backends_windows": ["vulkan", "rocm"], "backends_linux": ["vulkan", "rocm"]},
4
+ {"match": "RX 7900", "vendor": "amd", "arch": "rdna3",
5
+ "backends_windows": ["vulkan", "rocm"], "backends_linux": ["vulkan", "rocm"]},
6
+ {"match": "RX 6", "vendor": "amd", "arch": "rdna2",
7
+ "backends_windows": ["vulkan"], "backends_linux": ["vulkan", "rocm"]},
8
+ {"match": "RTX 50", "vendor": "nvidia", "arch": "blackwell",
9
+ "backends_windows": ["cuda", "vulkan"], "backends_linux": ["cuda", "vulkan"]},
10
+ {"match": "RTX 40", "vendor": "nvidia", "arch": "ada",
11
+ "backends_windows": ["cuda", "vulkan"], "backends_linux": ["cuda", "vulkan"]},
12
+ {"match": "RTX 30", "vendor": "nvidia", "arch": "ampere",
13
+ "backends_windows": ["cuda", "vulkan"], "backends_linux": ["cuda", "vulkan"]},
14
+ {"match": "GTX 10", "vendor": "nvidia", "arch": "pascal",
15
+ "backends_windows": ["cuda", "vulkan"], "backends_linux": ["cuda", "vulkan"]}
16
+ ]
@@ -0,0 +1,9 @@
1
+ {
2
+ "slug": "qwen3-0.6b", "family": "qwen3", "kind": "dense",
3
+ "n_layers": 28, "full_attn_layers": 28, "kv_heads": 8, "head_dim": 128,
4
+ "native_ctx": 32768,
5
+ "ggufs": [{"repo": "unsloth/Qwen3-0.6B-GGUF", "file": "Qwen3-0.6B-Q8_0.gguf",
6
+ "bytes": 639447744, "quant": "Q8_0"}],
7
+ "license": "apache-2.0", "use_cases": ["general"],
8
+ "sources": ["https://huggingface.co/unsloth/Qwen3-0.6B-GGUF"]
9
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "slug": "qwen3.6-35b-a3b", "family": "qwen3.6", "kind": "moe",
3
+ "n_layers": 40, "full_attn_layers": 10, "kv_heads": 2, "head_dim": 256,
4
+ "native_ctx": 262144,
5
+ "moe": {"total_b": 35, "active_b": 3, "expert_weight_fraction": 0.85},
6
+ "cache_type_policy": {"k": "q8_0", "v": "q8_0",
7
+ "reason": "DeltaNet recurrent state desyncs with q4 K-cache on long contexts"},
8
+ "ggufs": [
9
+ {"repo": "unsloth/Qwen3.6-35B-A3B-GGUF", "file": "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf",
10
+ "bytes": 22360456160, "quant": "UD-Q4_K_XL"},
11
+ {"repo": "unsloth/Qwen3.6-35B-A3B-GGUF", "file": "Qwen3.6-35B-A3B-UD-Q3_K_XL.gguf",
12
+ "bytes": 16845511648, "quant": "UD-Q3_K_XL"},
13
+ {"repo": "unsloth/Qwen3.6-35B-A3B-GGUF", "file": "Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf",
14
+ "bytes": 12290628576, "quant": "UD-Q2_K_XL"}
15
+ ],
16
+ "license": "apache-2.0", "use_cases": ["coding", "general", "agentic"],
17
+ "sources": ["https://huggingface.co/Qwen/Qwen3.6-35B-A3B",
18
+ "https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF"]
19
+ }
rigma/models.py ADDED
@@ -0,0 +1,130 @@
1
+ from __future__ import annotations
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+ STANDARD_GB = [4, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256]
6
+
7
+
8
+ def ram_tier(mb: int) -> int:
9
+ gb = mb / 1024
10
+ return min(STANDARD_GB, key=lambda s: abs(s - gb))
11
+
12
+
13
+ class GpuInfo(BaseModel):
14
+ vendor: str
15
+ name: str
16
+ vram_mb: int
17
+ arch: str = "unknown"
18
+ slug: str = "unknown"
19
+ backends: list[str] = Field(default_factory=list)
20
+
21
+
22
+ class CpuInfo(BaseModel):
23
+ cores: int
24
+ name: str = ""
25
+
26
+
27
+ class HardwareProfile(BaseModel):
28
+ gpus: list[GpuInfo]
29
+ ram_mb: int
30
+ ram_free_mb: int
31
+ cpu: CpuInfo
32
+ os: str # "windows" | "linux" | "darwin"
33
+ disk_free_gb: float
34
+
35
+ @property
36
+ def primary_gpu(self) -> GpuInfo | None:
37
+ return max(self.gpus, key=lambda g: g.vram_mb) if self.gpus else None
38
+
39
+ @property
40
+ def ram_tier_gb(self) -> int:
41
+ return ram_tier(self.ram_mb)
42
+
43
+ @property
44
+ def fingerprint(self) -> str:
45
+ gpu = self.primary_gpu
46
+ head = f"{gpu.vendor}-{gpu.slug}" if gpu else "cpu-only"
47
+ return f"{head}/ram-{self.ram_tier_gb}/{self.os}"
48
+
49
+
50
+ class MoESpec(BaseModel):
51
+ total_b: float
52
+ active_b: float
53
+ expert_weight_fraction: float
54
+
55
+
56
+ class CachePolicy(BaseModel):
57
+ k: str = "f16"
58
+ v: str = "f16"
59
+ reason: str = ""
60
+
61
+
62
+ class GgufFile(BaseModel):
63
+ repo: str
64
+ file: str
65
+ bytes: int
66
+ quant: str
67
+ sha256: str | None = None
68
+
69
+
70
+ class ModelSpec(BaseModel):
71
+ slug: str
72
+ family: str
73
+ kind: str # "dense" | "moe"
74
+ n_layers: int
75
+ full_attn_layers: int
76
+ kv_heads: int
77
+ head_dim: int
78
+ native_ctx: int
79
+ ggufs: list[GgufFile]
80
+ moe: MoESpec | None = None
81
+ cache_type_policy: CachePolicy = CachePolicy()
82
+ license: str = ""
83
+ use_cases: list[str] = Field(default_factory=list)
84
+ sources: list[str] = Field(default_factory=list)
85
+
86
+
87
+ class ComboFlags(BaseModel):
88
+ ctx: int
89
+ ngl: int = 99
90
+ n_cpu_moe: int = 0
91
+ flash_attn: bool = True
92
+ cache_type_k: str = "f16"
93
+ cache_type_v: str = "f16"
94
+
95
+
96
+ class Budget(BaseModel):
97
+ vram_mb: int
98
+ ram_mb: int
99
+
100
+
101
+ class Combo(BaseModel):
102
+ model: str
103
+ quant: str
104
+ backend: str
105
+ flags: ComboFlags
106
+ budget: Budget | None = None
107
+ expected: dict | None = None
108
+ verified: dict | None = None
109
+ notes: str = ""
110
+ sources: list[str] = Field(default_factory=list)
111
+
112
+
113
+ class RunPlan(BaseModel):
114
+ model_slug: str
115
+ gguf: GgufFile
116
+ backend: str
117
+ flags: ComboFlags
118
+ origin: str # "combo:<path>" | "class:<path>" | "calculator"
119
+ explain: list[str] = Field(default_factory=list)
120
+
121
+ def server_args(self, model_path: str, port: int) -> list[str]:
122
+ args = ["-m", model_path, "--port", str(port), "--host", "127.0.0.1",
123
+ "-ngl", str(self.flags.ngl), "-c", str(self.flags.ctx)]
124
+ if self.flags.n_cpu_moe > 0:
125
+ args += ["--n-cpu-moe", str(self.flags.n_cpu_moe)]
126
+ if self.flags.flash_attn:
127
+ args += ["-fa", "on"]
128
+ args += ["--cache-type-k", self.flags.cache_type_k,
129
+ "--cache-type-v", self.flags.cache_type_v]
130
+ return args
rigma/probe.py ADDED
@@ -0,0 +1,155 @@
1
+ from __future__ import annotations
2
+
3
+ import ctypes
4
+ import os
5
+ import platform
6
+ import re
7
+ import shutil
8
+
9
+ import psutil
10
+
11
+ from .models import CpuInfo, GpuInfo, HardwareProfile
12
+
13
+ VENDOR_IDS = {0x1002: "amd", 0x10DE: "nvidia", 0x8086: "intel", 0x106B: "apple"}
14
+
15
+
16
+ def _os_name() -> str:
17
+ return {"Windows": "windows", "Linux": "linux", "Darwin": "darwin"}.get(
18
+ platform.system(), "linux")
19
+
20
+
21
+ def _slugify(name: str, vram_mb: int) -> str:
22
+ s = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
23
+ return f"{s}-{round(vram_mb / 1024)}g"
24
+
25
+
26
+ def classify_gpu(raw: dict, gpu_table: list[dict], os_name: str) -> GpuInfo:
27
+ vendor = VENDOR_IDS.get(raw["vendor_id"], "unknown")
28
+ name, vram = raw["name"], raw["vram_mb"]
29
+ for row in gpu_table:
30
+ if row["match"].lower() in name.lower():
31
+ backends = row.get(f"backends_{os_name}",
32
+ row.get("backends_windows", ["vulkan"]))
33
+ return GpuInfo(vendor=row["vendor"], name=name, vram_mb=vram,
34
+ arch=row["arch"], slug=_slugify(name, vram),
35
+ backends=backends)
36
+ return GpuInfo(vendor=vendor, name=name, vram_mb=vram,
37
+ slug=_slugify(name, vram), backends=["vulkan"])
38
+
39
+
40
+ # --- Vulkan enumeration (ctypes; no SDK needed, the ICD ships with GPU drivers) ---
41
+
42
+ _VK_MEMORY_HEAP_DEVICE_LOCAL_BIT = 0x1
43
+
44
+
45
+ class _VkAppInfo(ctypes.Structure):
46
+ _fields_ = [("sType", ctypes.c_int), ("pNext", ctypes.c_void_p),
47
+ ("pApplicationName", ctypes.c_char_p),
48
+ ("applicationVersion", ctypes.c_uint32),
49
+ ("pEngineName", ctypes.c_char_p), ("engineVersion", ctypes.c_uint32),
50
+ ("apiVersion", ctypes.c_uint32)]
51
+
52
+
53
+ class _VkInstanceCreateInfo(ctypes.Structure):
54
+ _fields_ = [("sType", ctypes.c_int), ("pNext", ctypes.c_void_p),
55
+ ("flags", ctypes.c_uint32), ("pApplicationInfo", ctypes.c_void_p),
56
+ ("enabledLayerCount", ctypes.c_uint32),
57
+ ("ppEnabledLayerNames", ctypes.c_void_p),
58
+ ("enabledExtensionCount", ctypes.c_uint32),
59
+ ("ppEnabledExtensionNames", ctypes.c_void_p)]
60
+
61
+
62
+ class _VkPhysicalDeviceProperties(ctypes.Structure):
63
+ _fields_ = [("apiVersion", ctypes.c_uint32), ("driverVersion", ctypes.c_uint32),
64
+ ("vendorID", ctypes.c_uint32), ("deviceID", ctypes.c_uint32),
65
+ ("deviceType", ctypes.c_int), ("deviceName", ctypes.c_char * 256),
66
+ ("pipelineCacheUUID", ctypes.c_uint8 * 16),
67
+ ("limits", ctypes.c_uint8 * 504),
68
+ ("sparseProperties", ctypes.c_uint8 * 20)]
69
+
70
+
71
+ class _VkMemoryHeap(ctypes.Structure):
72
+ _fields_ = [("size", ctypes.c_uint64), ("flags", ctypes.c_uint32)]
73
+
74
+
75
+ class _VkMemoryType(ctypes.Structure):
76
+ _fields_ = [("propertyFlags", ctypes.c_uint32), ("heapIndex", ctypes.c_uint32)]
77
+
78
+
79
+ class _VkPhysicalDeviceMemoryProperties(ctypes.Structure):
80
+ _fields_ = [("memoryTypeCount", ctypes.c_uint32),
81
+ ("memoryTypes", _VkMemoryType * 32),
82
+ ("memoryHeapCount", ctypes.c_uint32),
83
+ ("memoryHeaps", _VkMemoryHeap * 16)]
84
+
85
+
86
+ def enumerate_vulkan() -> list[dict]:
87
+ """Enumerate GPUs via the Vulkan loader. Returns [] on any failure."""
88
+ try:
89
+ lib = ctypes.CDLL("vulkan-1" if _os_name() == "windows" else
90
+ ("libvulkan.dylib" if _os_name() == "darwin"
91
+ else "libvulkan.so.1"))
92
+ app = _VkAppInfo(sType=0, pApplicationName=b"rigma", apiVersion=(1 << 22))
93
+ info = _VkInstanceCreateInfo(sType=1, pApplicationInfo=ctypes.cast(
94
+ ctypes.pointer(app), ctypes.c_void_p))
95
+ inst = ctypes.c_void_p()
96
+ if lib.vkCreateInstance(ctypes.byref(info), None, ctypes.byref(inst)) != 0:
97
+ return []
98
+ try:
99
+ n = ctypes.c_uint32(0)
100
+ lib.vkEnumeratePhysicalDevices(inst, ctypes.byref(n), None)
101
+ devs = (ctypes.c_void_p * n.value)()
102
+ lib.vkEnumeratePhysicalDevices(inst, ctypes.byref(n), devs)
103
+ out = []
104
+ for d in devs:
105
+ props = _VkPhysicalDeviceProperties()
106
+ lib.vkGetPhysicalDeviceProperties(ctypes.c_void_p(d),
107
+ ctypes.byref(props))
108
+ mem = _VkPhysicalDeviceMemoryProperties()
109
+ lib.vkGetPhysicalDeviceMemoryProperties(ctypes.c_void_p(d),
110
+ ctypes.byref(mem))
111
+ local = [mem.memoryHeaps[i].size for i in range(mem.memoryHeapCount)
112
+ if mem.memoryHeaps[i].flags & _VK_MEMORY_HEAP_DEVICE_LOCAL_BIT]
113
+ if props.deviceType == 4: # VK_PHYSICAL_DEVICE_TYPE_CPU
114
+ continue
115
+ out.append({"vendor_id": props.vendorID,
116
+ "name": props.deviceName.decode(errors="replace"),
117
+ "vram_mb": int(max(local, default=0) / (1024 * 1024))})
118
+ return out
119
+ finally:
120
+ lib.vkDestroyInstance(inst, None)
121
+ except Exception:
122
+ return []
123
+
124
+
125
+ def _nvml_gpus() -> list[dict]:
126
+ try:
127
+ import pynvml
128
+ pynvml.nvmlInit()
129
+ out = []
130
+ for i in range(pynvml.nvmlDeviceGetCount()):
131
+ h = pynvml.nvmlDeviceGetHandleByIndex(i)
132
+ name = pynvml.nvmlDeviceGetName(h)
133
+ if isinstance(name, bytes):
134
+ name = name.decode()
135
+ out.append({"vendor_id": 0x10DE, "name": name,
136
+ "vram_mb": int(pynvml.nvmlDeviceGetMemoryInfo(h).total / 2**20)})
137
+ pynvml.nvmlShutdown()
138
+ return out
139
+ except Exception:
140
+ return []
141
+
142
+
143
+ def probe_hardware(gpu_table: list[dict],
144
+ raw_gpus: list[dict] | None = None) -> HardwareProfile:
145
+ os_name = _os_name()
146
+ raw = raw_gpus if raw_gpus is not None else (enumerate_vulkan() or _nvml_gpus())
147
+ vm = psutil.virtual_memory()
148
+ return HardwareProfile(
149
+ gpus=[classify_gpu(r, gpu_table, os_name) for r in raw],
150
+ ram_mb=int(vm.total / 2**20),
151
+ ram_free_mb=int(vm.available / 2**20),
152
+ cpu=CpuInfo(cores=os.cpu_count() or 1, name=platform.processor() or ""),
153
+ os=os_name,
154
+ disk_free_gb=shutil.disk_usage(os.path.expanduser("~")).free / 2**30,
155
+ )
rigma/registry.py ADDED
@@ -0,0 +1,44 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from importlib import resources
6
+ from pathlib import Path
7
+
8
+ from .models import Combo, ModelSpec
9
+
10
+
11
+ class Registry:
12
+ def __init__(self, gpus: list[dict], models: dict[str, ModelSpec],
13
+ combos: dict[str, Combo]):
14
+ self.gpus, self.models, self.combos = gpus, models, combos
15
+
16
+ @classmethod
17
+ def load(cls, path: Path | None = None) -> "Registry":
18
+ if path is None and os.environ.get("RIGMA_REGISTRY_DIR"):
19
+ path = Path(os.environ["RIGMA_REGISTRY_DIR"])
20
+ if path is None:
21
+ path = Path(str(resources.files("rigma").joinpath("data/registry")))
22
+ gpus = json.loads((path / "gpus.json").read_text(encoding="utf-8"))
23
+ models = {}
24
+ for f in sorted((path / "models").glob("*.json")):
25
+ spec = ModelSpec.model_validate_json(f.read_text(encoding="utf-8"))
26
+ models[spec.slug] = spec
27
+ combos = {}
28
+ for f in sorted((path / "combos").rglob("*.json")):
29
+ rel = f.relative_to(path / "combos").as_posix()
30
+ combos[rel] = Combo.model_validate_json(f.read_text(encoding="utf-8"))
31
+ return cls(gpus, models, combos)
32
+
33
+ def find_combo(self, vendor: str, gpu_slug: str, vram_gb: int, ram_gb: int,
34
+ use_case: str) -> tuple[Combo, str] | None:
35
+ candidates = [
36
+ f"{vendor}/{gpu_slug}/ram-{ram_gb}/{use_case}.json",
37
+ f"{vendor}/{gpu_slug}/ram-{ram_gb}/general.json",
38
+ f"_class/vram-{vram_gb}/ram-{ram_gb}/{use_case}.json",
39
+ f"_class/vram-{vram_gb}/ram-{ram_gb}/general.json",
40
+ ]
41
+ for rel in candidates:
42
+ if rel in self.combos:
43
+ return self.combos[rel], rel
44
+ return None
rigma/resolve.py ADDED
@@ -0,0 +1,106 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+ from .models import ComboFlags, GgufFile, HardwareProfile, ModelSpec, RunPlan
6
+ from .registry import Registry
7
+
8
+ VRAM_RESERVE_MB = {"windows": 1200, "linux": 400, "darwin": 0}
9
+ RAM_RESERVE_MB = 2048
10
+ COMPUTE_BUFFER_MB = 900
11
+ CACHE_BYTES = {"f16": 2.0, "q8_0": 1.0625, "q4_0": 0.5625}
12
+ CTX_DEFAULT = {"coding": 32768}
13
+ CTX_FLOOR = 8192
14
+
15
+
16
+ class ResolveError(RuntimeError):
17
+ pass
18
+
19
+
20
+ def kv_bytes_per_token(spec: ModelSpec, k: str, v: str) -> float:
21
+ per_side = spec.full_attn_layers * spec.kv_heads * spec.head_dim
22
+ return per_side * CACHE_BYTES[k] + per_side * CACHE_BYTES[v]
23
+
24
+
25
+ def _budgets(profile: HardwareProfile) -> tuple[float, float]:
26
+ gpu = profile.primary_gpu
27
+ vram = (gpu.vram_mb if gpu else 0) - VRAM_RESERVE_MB[profile.os] - COMPUTE_BUFFER_MB
28
+ return max(vram, 0), max(profile.ram_free_mb - RAM_RESERVE_MB, 0)
29
+
30
+
31
+ def fit_gguf(spec: ModelSpec, gguf: GgufFile, profile: HardwareProfile,
32
+ ctx: int, explain: list[str]) -> ComboFlags | None:
33
+ usable_vram, usable_ram = _budgets(profile)
34
+ k, v = spec.cache_type_policy.k, spec.cache_type_policy.v
35
+ file_mb = gguf.bytes / 2**20
36
+ kv_mb = ctx * kv_bytes_per_token(spec, k, v) / 2**20
37
+ explain.append(f"{gguf.quant}@ctx{ctx}: file={file_mb:.0f}MB kv={kv_mb:.0f}MB "
38
+ f"vs vram={usable_vram:.0f}MB ram={usable_ram:.0f}MB")
39
+ if spec.moe is None:
40
+ if file_mb + kv_mb <= usable_vram:
41
+ return ComboFlags(ctx=ctx, cache_type_k=k, cache_type_v=v)
42
+ return None
43
+ expert_mb = file_mb * spec.moe.expert_weight_fraction
44
+ per_layer = expert_mb / spec.n_layers
45
+ need_off = max(0.0, file_mb + kv_mb - usable_vram)
46
+ n_off = math.ceil(need_off / per_layer) if need_off else 0
47
+ if n_off <= spec.n_layers and n_off * per_layer <= usable_ram:
48
+ return ComboFlags(ctx=ctx, n_cpu_moe=n_off, cache_type_k=k, cache_type_v=v)
49
+ return None
50
+
51
+
52
+ def _backend(profile: HardwareProfile) -> str:
53
+ gpu = profile.primary_gpu
54
+ return gpu.backends[0] if gpu and gpu.backends else "cpu"
55
+
56
+
57
+ def _calculate(profile: HardwareProfile, registry: Registry,
58
+ use_case: str) -> RunPlan | None:
59
+ explain: list[str] = []
60
+ pool = [m for m in registry.models.values() if use_case in m.use_cases] or \
61
+ list(registry.models.values())
62
+
63
+ def total_b(m: ModelSpec) -> float:
64
+ return m.moe.total_b if m.moe else m.n_layers
65
+
66
+ for spec in sorted(pool, key=total_b, reverse=True):
67
+ for gguf in spec.ggufs: # registry order: largest quant first
68
+ ctx = min(CTX_DEFAULT.get(use_case, 16384), spec.native_ctx)
69
+ while ctx >= CTX_FLOOR:
70
+ flags = fit_gguf(spec, gguf, profile, ctx, explain)
71
+ if flags:
72
+ return RunPlan(model_slug=spec.slug, gguf=gguf,
73
+ backend=_backend(profile), flags=flags,
74
+ origin="calculator", explain=explain)
75
+ ctx //= 2
76
+ return None
77
+
78
+
79
+ def resolve(profile: HardwareProfile, registry: Registry,
80
+ use_case: str = "general", model_override: str | None = None) -> RunPlan:
81
+ if not registry.models:
82
+ raise ResolveError("registry has no models")
83
+ gpu = profile.primary_gpu
84
+ if gpu and model_override is None:
85
+ hit = registry.find_combo(gpu.vendor, gpu.slug, round(gpu.vram_mb / 1024),
86
+ profile.ram_tier_gb, use_case)
87
+ if hit:
88
+ combo, rel = hit
89
+ spec = registry.models[combo.model]
90
+ gguf = next(g for g in spec.ggufs if g.quant == combo.quant)
91
+ kind = "class" if rel.startswith("_class/") else "combo"
92
+ return RunPlan(model_slug=combo.model, gguf=gguf, backend=combo.backend,
93
+ flags=combo.flags, origin=f"{kind}:{rel}",
94
+ explain=[f"registry match: {rel}"] + combo.sources)
95
+ if model_override:
96
+ registry = Registry(registry.gpus,
97
+ {model_override: registry.models[model_override]},
98
+ registry.combos)
99
+ plan = _calculate(profile, registry, use_case)
100
+ if plan:
101
+ return plan
102
+ # absolute floor: smallest model, smallest quant, CPU
103
+ spec = min(registry.models.values(), key=lambda m: m.ggufs[-1].bytes)
104
+ return RunPlan(model_slug=spec.slug, gguf=spec.ggufs[-1], backend="cpu",
105
+ flags=ComboFlags(ctx=CTX_FLOOR, ngl=0), origin="calculator",
106
+ explain=["floor: nothing larger fits"])
rigma/runtime.py ADDED
@@ -0,0 +1,143 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import subprocess
7
+ import tarfile
8
+ import time
9
+ import zipfile
10
+ from importlib import resources
11
+ from pathlib import Path
12
+
13
+ import httpx
14
+ from huggingface_hub import hf_hub_download
15
+
16
+ from .models import GgufFile, RunPlan
17
+
18
+
19
+ def rigma_home() -> Path:
20
+ return Path(os.environ.get("RIGMA_HOME", str(Path.home() / ".rigma")))
21
+
22
+
23
+ def _engines_manifest() -> dict:
24
+ return json.loads(resources.files("rigma").joinpath("data/engines.json")
25
+ .read_text(encoding="utf-8"))
26
+
27
+
28
+ def _fetch(url: str, dest: Path) -> None:
29
+ with httpx.stream("GET", url, follow_redirects=True, timeout=600) as r:
30
+ r.raise_for_status()
31
+ with open(dest, "wb") as f:
32
+ for chunk in r.iter_bytes(1 << 20):
33
+ f.write(chunk)
34
+
35
+
36
+ def _extract(archive: Path, dest: Path) -> None:
37
+ if archive.name.endswith(".zip"):
38
+ with zipfile.ZipFile(archive) as z:
39
+ z.extractall(dest)
40
+ else:
41
+ with tarfile.open(archive) as t:
42
+ t.extractall(dest, filter="data")
43
+
44
+
45
+ def ensure_engine(backend: str, os_name: str) -> Path:
46
+ man = _engines_manifest()
47
+ key = f"{os_name}/{backend}"
48
+ if key not in man["assets"]:
49
+ raise RuntimeError(f"no pinned engine build for {key}")
50
+ root = rigma_home() / "engines" / man["version"] / backend
51
+ exe = root / ("llama-server.exe" if os_name == "windows" else "llama-server")
52
+ if exe.exists():
53
+ return exe
54
+ found = next(root.rglob(exe.name), None) if root.exists() else None
55
+ if found:
56
+ return found
57
+ root.mkdir(parents=True, exist_ok=True)
58
+ lock_path = rigma_home() / "engines" / "lock.json"
59
+ lock = json.loads(lock_path.read_text()) if lock_path.exists() else {}
60
+ assets = [man["assets"][key]] + man.get("extra_assets", {}).get(key, [])
61
+ for asset in assets:
62
+ archive = root / asset
63
+ _fetch(man["url_base"] + asset, archive)
64
+ digest = hashlib.sha256(archive.read_bytes()).hexdigest()
65
+ lock_key = f"{key}:{asset}" if asset != man["assets"][key] else key
66
+ if lock_key in lock and lock[lock_key]["sha256"] != digest:
67
+ archive.unlink()
68
+ raise RuntimeError(f"checksum mismatch for {asset}: expected "
69
+ f"{lock[lock_key]['sha256']}, got {digest}")
70
+ lock[lock_key] = {"asset": asset, "sha256": digest,
71
+ "version": man["version"]}
72
+ _extract(archive, root)
73
+ archive.unlink()
74
+ lock_path.write_text(json.dumps(lock, indent=2))
75
+ if exe.exists():
76
+ return exe
77
+ found = next(root.rglob(exe.name), None) # some archives nest under build/bin/
78
+ if not found:
79
+ raise RuntimeError(f"{exe.name} not found in downloaded engine assets")
80
+ return found
81
+
82
+
83
+ def ensure_model(gguf: GgufFile) -> Path:
84
+ # Polite + robust by default: HF's xet backend opens ~16 parallel range
85
+ # requests (saturates home connections) and was observed to hang and lose
86
+ # resume state after interrupted runs (2026-07-06). The classic downloader
87
+ # is single-stream and resumes deterministically. `rigma up --turbo`
88
+ # re-enables xet at full concurrency.
89
+ os.environ.setdefault("HF_HUB_DISABLE_XET", "1")
90
+ os.environ.setdefault("HF_XET_NUM_CONCURRENT_RANGE_GETS", "4")
91
+ local_dir = rigma_home() / "models"
92
+ local_dir.mkdir(parents=True, exist_ok=True)
93
+ return Path(hf_hub_download(repo_id=gguf.repo, filename=gguf.file,
94
+ local_dir=str(local_dir)))
95
+
96
+
97
+ class ServerProcess:
98
+ def __init__(self, proc: subprocess.Popen, port: int, log_path: Path):
99
+ self.proc, self.port, self.log_path = proc, port, log_path
100
+
101
+ @property
102
+ def url(self) -> str:
103
+ return f"http://127.0.0.1:{self.port}"
104
+
105
+ def is_healthy(self) -> bool:
106
+ try:
107
+ return httpx.get(f"{self.url}/health", timeout=3).status_code == 200
108
+ except Exception:
109
+ return False
110
+
111
+ def stop(self) -> None:
112
+ self.proc.terminate()
113
+ try:
114
+ self.proc.wait(timeout=10)
115
+ except subprocess.TimeoutExpired:
116
+ self.proc.kill()
117
+
118
+
119
+ def launch_server(exe: Path, plan: RunPlan, model_path: Path, port: int = 11500,
120
+ timeout: float = 300.0,
121
+ extra_args: list[str] | None = None) -> ServerProcess:
122
+ logs = rigma_home() / "logs"
123
+ sessions = rigma_home() / "sessions"
124
+ logs.mkdir(parents=True, exist_ok=True)
125
+ sessions.mkdir(parents=True, exist_ok=True)
126
+ log_path = logs / f"server-{port}.log"
127
+ argv = [str(exe), *(extra_args or []),
128
+ *plan.server_args(str(model_path), port),
129
+ "--slot-save-path", str(sessions)]
130
+ with open(log_path, "w", encoding="utf-8", errors="replace") as log_f:
131
+ proc = subprocess.Popen(argv, stdout=log_f, stderr=subprocess.STDOUT)
132
+ sp = ServerProcess(proc, port, log_path)
133
+ deadline = time.monotonic() + timeout
134
+ while time.monotonic() < deadline:
135
+ if proc.poll() is not None:
136
+ break
137
+ if sp.is_healthy():
138
+ return sp
139
+ time.sleep(0.5)
140
+ sp.stop()
141
+ tail = "".join(log_path.read_text(encoding="utf-8",
142
+ errors="replace").splitlines(True)[-40:])
143
+ raise RuntimeError(f"llama-server failed to become healthy on :{port}\n{tail}")
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.4
2
+ Name: rigma
3
+ Version: 0.1.0
4
+ Summary: Hardware-aware local LLM deployment: probe, resolve, run.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: httpx>=0.27
9
+ Requires-Dist: huggingface-hub>=0.23
10
+ Requires-Dist: psutil>=5.9
11
+ Requires-Dist: pydantic>=2.7
12
+ Requires-Dist: typer>=0.12
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=8; extra == 'dev'
15
+ Requires-Dist: ruff>=0.4; extra == 'dev'
16
+ Provides-Extra: nvidia
17
+ Requires-Dist: pynvml>=11.5; extra == 'nvidia'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # Rigma
21
+
22
+ Hardware-aware local LLM deployment for consumer machines: `rigma up` probes your GPU/RAM,
23
+ picks the community-verified best model + quant + flag combo for your exact hardware,
24
+ downloads a pinned llama.cpp build and the model, and serves an OpenAI-compatible endpoint —
25
+ no knob-mashing required.
26
+
27
+ Unlike generic runners, Rigma applies the tuning that actually matters per machine:
28
+ MoE expert offload (`--n-cpu-moe`) sized to your RAM, architecture-aware KV-cache policies
29
+ (e.g. `q8_0` K-cache floor on DeltaNet-family models), backend selection per GPU generation
30
+ (e.g. Vulkan over ROCm on RDNA4), flash attention, and session persistence
31
+ (`--slot-save-path`) on by default. Every decision is auditable: `rigma plan --explain`
32
+ shows the arithmetic and sources.
33
+
34
+ ## Quickstart (pre-alpha)
35
+
36
+ ```powershell
37
+ git clone https://github.com/IxMxAMAR/rigma && cd rigma
38
+ pip install -e .
39
+ rigma up # probe -> resolve -> download -> serve at http://127.0.0.1:11500/v1
40
+ ```
41
+
42
+ Commands: `rigma doctor` (what Rigma sees), `rigma plan --explain` (what it would run and why),
43
+ `rigma models` (what fits your machine), `rigma up --use-case coding` (serve).
44
+
45
+ ## Status
46
+
47
+ Pre-alpha (M1). Verified combos:
48
+
49
+ | Hardware | Model | Backend | Result |
50
+ |---|---|---|---|
51
+ | RX 9070 XT 16GB + 16GB RAM (Windows) | Qwen3.6-35B-A3B UD-Q3_K_XL, ctx 32K, n_cpu_moe 10 | Vulkan (llama.cpp b9867) | **verified 2026-07-06**: 57.1 t/s gen, 689 t/s prefill @ 4K prompt |
52
+
53
+ Design: `docs/superpowers/specs/2026-07-03-rigma-design.md`. License: Apache-2.0.
54
+ RAG integration (via [Raggity](https://github.com/IxMxAMAR/raggity), AGPL-3.0, separate process) lands in M4.
@@ -0,0 +1,19 @@
1
+ rigma/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ rigma/cli.py,sha256=e_Qohd-C5uF4xNI2aAJD2Vn4aJkN3ExVQ-FZV66B6fw,3503
3
+ rigma/models.py,sha256=pYtXUuoT92UZm0yLW2NsVwNBvQEmq6WZe5phZG55-do,3091
4
+ rigma/probe.py,sha256=u1wxdBQkIscxlwIDCTr-MqxSP_pZttGeMkBAUQGBXWs,6321
5
+ rigma/registry.py,sha256=dkyj5F2Pp_3FPg4pczi7YQhKWx4-Wz17Oa89uPi8aF0,1762
6
+ rigma/resolve.py,sha256=lyf7I7R-cMxz0uelnfTbNR2HARYKjDo1WeyvvSXDKBQ,4539
7
+ rigma/runtime.py,sha256=L41gZwaz03wYpo5wE8e1ZnhVHRmwcNxWnEAymmQUh3o,5334
8
+ rigma/data/engines.json,sha256=HaQIU55L33poCmwwlvnVFK7gXY710unhs0M9mZiIhc4,566
9
+ rigma/data/registry/gpus.json,sha256=-RYx7WZV3Mjizv3uB_TLcNpO3StcaqwglFbKTJM6SvU,977
10
+ rigma/data/registry/combos/_class/vram-16/ram-16/general.json,sha256=Z6rAneTSHyPOmZjlEFxxmhLCoz2eWIrT6fErdvF6I4Q,374
11
+ rigma/data/registry/combos/amd/amd-radeon-rx-9070-xt-16g/ram-16/coding.json,sha256=Yo8wI5nbz5xoyO0MUGH2l1bogEIEOgPhsVR8X5ypnI8,749
12
+ rigma/data/registry/combos/amd/amd-radeon-rx-9070-xt-16g/ram-16/general.json,sha256=2WDinapPnq7vE7Bzi9mopfdj05nG10wsG3g_onqCOMk,542
13
+ rigma/data/registry/models/qwen3-0.6b.json,sha256=zJIkoA5cB1V7Lqk6ePb3B0kuaRiu0SB3e99nCWOstfw,410
14
+ rigma/data/registry/models/qwen3.6-35b-a3b.json,sha256=5ZdhlsVlzWL1s_9pBtuyudUkv6YzZaQRnhP3kuNvmMY,1012
15
+ rigma-0.1.0.dist-info/METADATA,sha256=ROj42G-e5deQJKBzqNt5M3X0cFdCXUquVJQkFUqfa0Q,2195
16
+ rigma-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
17
+ rigma-0.1.0.dist-info/entry_points.txt,sha256=BKJ-KRvuElfowivFjws8v0UEcTrCEoPtKYETCfe3bEs,40
18
+ rigma-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
19
+ rigma-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ rigma = rigma.cli:app
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.