langset 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.
langset/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """langset — few-shot fine-tune an LLM to emit a latent into a bespoke, specialized geometry.
2
+
3
+ The trained model is Sentence-Transformer-shaped, so it drops into SetFit as a `model_body`.
4
+ """
5
+ from langset.modeling import EmitHead, LangSetModel
6
+ from langset.trainer import Trainer
7
+ from langset.training_args import TrainingArguments
8
+
9
+ __all__ = ["LangSetModel", "EmitHead", "Trainer", "TrainingArguments"]
10
+ __version__ = "0.1.0"
langset/data.py ADDED
@@ -0,0 +1,29 @@
1
+ """Dataset contract for langset.
2
+
3
+ A training example is a row with:
4
+ - `input_text` : the text you'll have at inference (e.g. a name, a query, a review)
5
+ - `target_text` : a description of the SAME item that defines where it should land (embedded by the
6
+ bootstrap encoder to seed the geometry). Point this at something `input_text` can't
7
+ trivially regenerate, or you're just distilling a text encoder.
8
+ - any number of optional label columns : EVAL-ONLY geometry probes (kNN-purity at validation). They never
9
+ enter training — training on them would collapse the geometry onto the labels.
10
+
11
+ Pass a `datasets.Dataset` or a `list[dict]` to `Trainer`; use `column_mapping` to rename your columns onto
12
+ `input_text` / `target_text`.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from typing import Any, Optional
17
+
18
+
19
+ def from_records(records: list[dict[str, Any]], input_key: str, target_key: str,
20
+ label_keys: Optional[list[str]] = None) -> list[dict[str, Any]]:
21
+ """Convenience: project a list of dicts onto the langset contract."""
22
+ label_keys = label_keys or []
23
+ out = []
24
+ for r in records:
25
+ row = {"input_text": str(r[input_key]), "target_text": str(r[target_key])}
26
+ for k in label_keys:
27
+ row[k] = r.get(k, "unknown")
28
+ out.append(row)
29
+ return out
langset/modeling.py ADDED
@@ -0,0 +1,163 @@
1
+ """LangSetModel: an LLM (LoRA) + a learned emit head that maps input text -> a latent in a bespoke geometry.
2
+
3
+ The output is Sentence-Transformer-shaped (`encode`, `get_sentence_embedding_dimension`, `as_sentence_transformer`)
4
+ so the trained model drops straight into SetFit as a `model_body`.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+ from typing import Any, Optional, Union
10
+
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from torch import nn
15
+
16
+
17
+ class EmitHead(nn.Module):
18
+ """Learned query tokens whose post-backbone hidden states are read out as the latent (the LLM's vector 'mouth').
19
+
20
+ `dropout` is trained ON when >0 so MC-dropout could later serve as an uncertainty signal; it's also plain
21
+ regularization. The head stays fp32 even when the backbone is bf16.
22
+ """
23
+
24
+ def __init__(self, h: int, d: int, n_emit: int = 4, dropout: float = 0.0) -> None:
25
+ super().__init__()
26
+ self.n_emit = n_emit
27
+ self.q = nn.Parameter(torch.randn(n_emit, h) * 0.02)
28
+ self.drop = nn.Dropout(dropout)
29
+ self.out = nn.Linear(n_emit * h, d)
30
+
31
+ def forward(self, hid_emit: torch.Tensor) -> torch.Tensor: # [B, n_emit, h] -> [B, d]
32
+ flat = self.drop(hid_emit.reshape(hid_emit.size(0), -1).float())
33
+ return F.normalize(self.out(flat), p=2, dim=-1)
34
+
35
+
36
+ def build_backbone(llm_model: str, lora_r: int, dropout: float, bf16: bool, dev: str) -> Any:
37
+ from peft import LoraConfig, get_peft_model # type: ignore[import-untyped]
38
+ from transformers import AutoModelForCausalLM # type: ignore[import-untyped]
39
+ dt = torch.bfloat16 if bf16 else torch.float32
40
+ base = AutoModelForCausalLM.from_pretrained(
41
+ llm_model, torch_dtype=dt, attention_dropout=dropout, attn_implementation="sdpa").to(dev)
42
+ lora = LoraConfig(r=lora_r, lora_alpha=2 * lora_r, lora_dropout=dropout, bias="none",
43
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
44
+ "gate_proj", "up_proj", "down_proj"])
45
+ return get_peft_model(base, lora)
46
+
47
+
48
+ class LangSetModel(nn.Module):
49
+ """LLM backbone (LoRA) + EmitHead. `from_pretrained` infers the latent dim from the bootstrap encoder, so the
50
+ emitted geometry starts in that encoder's space (the Trainer then EMA-specializes it away)."""
51
+
52
+ def __init__(self, backbone: Any, tokenizer: Any, latent_dim: int, n_emit: int,
53
+ llm_model: str, bootstrap_model: str, dropout: float = 0.0, max_len: int = 512) -> None:
54
+ super().__init__()
55
+ self.backbone = backbone
56
+ self.tokenizer = tokenizer
57
+ self.embed = backbone.get_input_embeddings()
58
+ self.h = int(backbone.config.hidden_size)
59
+ self.latent_dim = latent_dim
60
+ self.head = EmitHead(self.h, latent_dim, n_emit, dropout)
61
+ self.llm_model = llm_model
62
+ self.bootstrap_model = bootstrap_model
63
+ self.max_len = max_len
64
+ self._bootstrap: Any = None
65
+
66
+ # ---- construction ----
67
+ @classmethod
68
+ def from_pretrained(cls, llm_model: str, bootstrap_model: str, *, latent_dim: Optional[int] = None,
69
+ n_emit: int = 4, lora_r: int = 16, dropout: float = 0.0, bf16: bool = False,
70
+ max_len: int = 512, device: Optional[str] = None) -> "LangSetModel":
71
+ from sentence_transformers import SentenceTransformer # type: ignore[import-untyped]
72
+ from transformers import AutoTokenizer # type: ignore[import-untyped]
73
+ dev = device or ("cuda" if torch.cuda.is_available() else "cpu")
74
+ tok = AutoTokenizer.from_pretrained(llm_model)
75
+ if tok.pad_token_id is None:
76
+ tok.pad_token = tok.eos_token
77
+ if latent_dim is None: # target space dim = bootstrap encoder dim
78
+ _st = SentenceTransformer(bootstrap_model) # ST renamed the method in 4.x -> support both
79
+ _dim = getattr(_st, "get_embedding_dimension", None) or _st.get_sentence_embedding_dimension
80
+ latent_dim = int(_dim())
81
+ backbone = build_backbone(llm_model, lora_r, dropout, bf16, dev)
82
+ m = cls(backbone, tok, latent_dim, n_emit, llm_model, bootstrap_model, dropout, max_len).to(dev)
83
+ return m
84
+
85
+ @property
86
+ def device(self) -> torch.device:
87
+ return next(self.backbone.parameters()).device
88
+
89
+ @property
90
+ def bootstrap_encoder(self) -> Any:
91
+ """Lazily-loaded target encoder (used by the Trainer for targets + the beats-bootstrap baseline)."""
92
+ if self._bootstrap is None:
93
+ from sentence_transformers import SentenceTransformer # type: ignore[import-untyped]
94
+ self._bootstrap = SentenceTransformer(self.bootstrap_model, device=str(self.device))
95
+ return self._bootstrap
96
+
97
+ # ---- forward / inference ----
98
+ def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
99
+ rev = self.embed(input_ids)
100
+ q = self.head.q.unsqueeze(0).expand(input_ids.size(0), -1, -1).to(rev.dtype)
101
+ emb = torch.cat([rev, q], 1)
102
+ am = torch.cat([attention_mask,
103
+ torch.ones(input_ids.size(0), self.head.n_emit, device=input_ids.device,
104
+ dtype=attention_mask.dtype)], 1)
105
+ hid = self.backbone(inputs_embeds=emb, attention_mask=am, output_hidden_states=True).hidden_states[-1]
106
+ return self.head(hid[:, -self.head.n_emit:, :])
107
+
108
+ @torch.no_grad()
109
+ def encode(self, sentences: Union[str, list[str]], batch_size: int = 32, convert_to_numpy: bool = True,
110
+ normalize_embeddings: bool = True, show_progress_bar: bool = False,
111
+ device: Optional[str] = None) -> Union[np.ndarray, torch.Tensor]:
112
+ """Sentence-Transformer-compatible. This is the method SetFit calls on its body."""
113
+ single = isinstance(sentences, str)
114
+ texts = [sentences] if single else list(sentences)
115
+ was_training = self.training
116
+ self.eval()
117
+ out: list[torch.Tensor] = []
118
+ for i in range(0, len(texts), batch_size):
119
+ enc = self.tokenizer(texts[i:i + batch_size], padding=True, truncation=True,
120
+ max_length=self.max_len, return_tensors="pt").to(self.device)
121
+ z = self(enc["input_ids"], enc["attention_mask"])
122
+ if normalize_embeddings:
123
+ z = F.normalize(z, p=2, dim=-1)
124
+ out.append(z.cpu())
125
+ if was_training:
126
+ self.train()
127
+ emb = torch.cat(out)
128
+ emb = emb[0] if single else emb
129
+ return emb.numpy() if convert_to_numpy else emb
130
+
131
+ def emit(self, sentences: Union[str, list[str]], **kw: Any) -> torch.Tensor:
132
+ return self.encode(sentences, convert_to_numpy=False, **kw) # type: ignore[return-value]
133
+
134
+ def get_sentence_embedding_dimension(self) -> int:
135
+ return self.latent_dim
136
+
137
+ def as_sentence_transformer(self) -> Any:
138
+ """Wrap as a `sentence_transformers.SentenceTransformer` so it drops into SetFit as `model_body`."""
139
+ from langset.st_module import to_sentence_transformer
140
+ return to_sentence_transformer(self)
141
+
142
+ # ---- persistence (LoRA + head + config; backbone/bootstrap rebuilt from ids) ----
143
+ def save_pretrained(self, path: Union[str, Path]) -> None:
144
+ import json
145
+ p = Path(path); p.mkdir(parents=True, exist_ok=True)
146
+ torch.save({"head": self.head.state_dict(),
147
+ "lora": {k: v.cpu() for k, v in self.backbone.state_dict().items() if "lora" in k}},
148
+ p / "langset.pt")
149
+ (p / "config.json").write_text(json.dumps({
150
+ "llm_model": self.llm_model, "bootstrap_model": self.bootstrap_model,
151
+ "latent_dim": self.latent_dim, "n_emit": self.head.n_emit, "max_len": self.max_len}))
152
+
153
+ @classmethod
154
+ def load(cls, path: Union[str, Path], *, lora_r: int = 16, device: Optional[str] = None) -> "LangSetModel":
155
+ import json
156
+ p = Path(path); cfg = json.loads((p / "config.json").read_text())
157
+ m = cls.from_pretrained(cfg["llm_model"], cfg["bootstrap_model"], latent_dim=cfg["latent_dim"],
158
+ n_emit=cfg["n_emit"], lora_r=lora_r, max_len=cfg["max_len"], device=device)
159
+ sd = torch.load(p / "langset.pt", map_location=m.device, weights_only=False)
160
+ m.backbone.load_state_dict(sd["lora"], strict=False)
161
+ m.head.load_state_dict(sd["head"])
162
+ m.eval()
163
+ return m
langset/selection.py ADDED
@@ -0,0 +1,81 @@
1
+ """Validation / early-stop metrics. The hard-won rules:
2
+ - NEVER select on training loss (InfoNCE+EMA can minimize it by COLLAPSING the geometry).
3
+ - NEVER score retrieval against the frozen bootstrap targets (the model specializes AWAY from them).
4
+ - Score on held-out, in the CURRENT geometry: retrieval mrr + a collapse guard; and, when the rows carry
5
+ geometry labels, held-out kNN purity (+ beats-bootstrap), which is the preferred, intent-aligned selector.
6
+ Geometry labels are EVAL-ONLY probes — they never enter training (training on them would collapse the space).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Optional
11
+
12
+ import numpy as np
13
+
14
+
15
+ def retrieval_mrr(pred: np.ndarray, bank: np.ndarray) -> dict[str, float]:
16
+ """Each pred[i] should retrieve target bank[i] among the val set (rank-based, scale-free, collapse-sensitive)."""
17
+ sims = pred @ bank.T
18
+ truth = np.arange(len(pred))
19
+ order = np.argsort(-sims, axis=1)
20
+ rank = np.array([int(np.where(order[i] == truth[i])[0][0]) for i in range(len(truth))])
21
+ return {"r@1": float((rank == 0).mean()), "mrr": float((1.0 / (rank + 1)).mean())}
22
+
23
+
24
+ def collapse_score(X: np.ndarray) -> float:
25
+ """Mean off-diagonal cosine of (normalized) emissions. ->1 means collapsed; healthy spaces sit low."""
26
+ Xn = X / (np.linalg.norm(X, axis=1, keepdims=True) + 1e-9)
27
+ s = Xn @ Xn.T
28
+ np.fill_diagonal(s, np.nan)
29
+ return float(np.nanmean(s))
30
+
31
+
32
+ def knn_purity(X: np.ndarray, labels: list[str], k: int = 5) -> float:
33
+ """Leave-one-out majority-vote accuracy by label (does the geometry organize by this attribute?)."""
34
+ keep = [i for i, l in enumerate(labels) if str(l) not in ("", "unknown", "none", "nan")]
35
+ if len(keep) < k + 2:
36
+ return float("nan")
37
+ Xk = X[keep] / (np.linalg.norm(X[keep], axis=1, keepdims=True) + 1e-9)
38
+ lk = [labels[i] for i in keep]
39
+ sims = Xk @ Xk.T
40
+ np.fill_diagonal(sims, -1e9)
41
+ nn = np.argsort(-sims, axis=1)[:, :k]
42
+ correct = sum(max(set(v := [lk[j] for j in row]), key=v.count) == lk[i] for i, row in enumerate(nn))
43
+ return correct / len(keep)
44
+
45
+
46
+ def evaluate(emit_val: np.ndarray, target_val: np.ndarray, label_cols: dict[str, list[str]],
47
+ bootstrap_val: Optional[np.ndarray], select: str) -> dict[str, Any]:
48
+ """Compute all val signals + the scalar `score` used for selection/early-stop."""
49
+ out: dict[str, Any] = {}
50
+ out.update(retrieval_mrr(emit_val, target_val))
51
+ out["collapse"] = collapse_score(emit_val)
52
+ have_labels = len(label_cols) > 0
53
+ if have_labels:
54
+ beaten, purities = 0, []
55
+ for name, labels in label_cols.items():
56
+ pe = knn_purity(emit_val, labels)
57
+ out[f"purity/{name}"] = pe
58
+ if pe == pe:
59
+ purities.append(pe)
60
+ if bootstrap_val is not None:
61
+ pb = knn_purity(bootstrap_val, labels)
62
+ out[f"purity_bootstrap/{name}"] = pb
63
+ beaten += int(pe > pb)
64
+ out["purity_mean"] = float(np.mean(purities)) if purities else float("nan")
65
+ out["beats_bootstrap"] = beaten
66
+
67
+ mode = select
68
+ if mode == "auto":
69
+ mode = "purity" if have_labels else "retrieval"
70
+ if mode == "purity" and have_labels:
71
+ score = out.get("beats_bootstrap", 0) + (out.get("purity_mean", 0.0) or 0.0)
72
+ elif mode == "loss":
73
+ score = -out["collapse"] # discouraged; at least penalize collapse
74
+ else:
75
+ score = out["mrr"]
76
+ # collapse guard: a fully collapsed geometry is never "best"
77
+ if out["collapse"] > 0.95:
78
+ score = -1.0
79
+ out["score"] = float(score)
80
+ out["select_mode"] = mode
81
+ return out
langset/st_module.py ADDED
@@ -0,0 +1,62 @@
1
+ """Wrap a trained LangSetModel as a `sentence_transformers.SentenceTransformer` so it drops into SetFit as the
2
+ `model_body`:
3
+
4
+ body = langset_model.as_sentence_transformer()
5
+ setfit_model = SetFitModel(model_body=body, labels=[...])
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ import torch
12
+ from torch import nn
13
+
14
+
15
+ class LangSetSTModule(nn.Module):
16
+ """A Sentence-Transformers custom module: tokenizes text and emits the langset latent as `sentence_embedding`."""
17
+
18
+ def __init__(self, model: Any) -> None:
19
+ super().__init__()
20
+ self.model = model # registered submodule -> .to(device) propagates
21
+ # attributes SentenceTransformer / SetFit's trainer expect a body to expose
22
+ self.tokenizer = model.tokenizer
23
+ self.auto_model = model.backbone
24
+ self.max_seq_length = model.max_len
25
+
26
+ def forward(self, features: dict[str, Any]) -> dict[str, Any]:
27
+ z = self.model(features["input_ids"], features["attention_mask"])
28
+ features["sentence_embedding"] = z
29
+ return features
30
+
31
+ def tokenize(self, texts: list[str], **kw: Any) -> dict[str, torch.Tensor]:
32
+ enc = self.model.tokenizer(list(texts), padding=True, truncation=True,
33
+ max_length=self.model.max_len, return_tensors="pt")
34
+ return {"input_ids": enc["input_ids"], "attention_mask": enc["attention_mask"]}
35
+
36
+ def get_sentence_embedding_dimension(self) -> int:
37
+ return int(self.model.latent_dim)
38
+
39
+ def get_embedding_dimension(self) -> int: # ST 4.x name
40
+ return int(self.model.latent_dim)
41
+
42
+ def get_config_dict(self) -> dict[str, Any]:
43
+ return {}
44
+
45
+ def save(self, output_path: str, **kw: Any) -> None:
46
+ self.model.save_pretrained(output_path)
47
+
48
+ @staticmethod
49
+ def load(input_path: str, **kw: Any) -> "LangSetSTModule":
50
+ from langset.modeling import LangSetModel
51
+ return LangSetSTModule(LangSetModel.load(input_path))
52
+
53
+
54
+ def to_sentence_transformer(model: Any) -> Any:
55
+ from sentence_transformers import SentenceTransformer # type: ignore[import-untyped]
56
+ st = SentenceTransformer(modules=[LangSetSTModule(model)], device=str(model.device))
57
+ for attr, val in (("tokenizer", model.tokenizer), ("max_seq_length", model.max_len)):
58
+ try: # some ST versions expect these on the ST object
59
+ setattr(st, attr, val)
60
+ except Exception: # noqa: BLE001 - it's a read-only property -> already resolves
61
+ pass
62
+ return st
langset/trainer.py ADDED
@@ -0,0 +1,135 @@
1
+ """Trainer: bootstrap the target geometry from the bootstrap encoder, contrastively fit the LLM emitter, and
2
+ EMA-specialize the geometry away from the seed. Selects/early-stops on held-out geometry (see selection.py),
3
+ never on training loss.
4
+
5
+ Dataset rows: `input_text`, `target_text`, plus optional geometry-label columns (EVAL-ONLY probes).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+ from typing import Any, Optional, Union
11
+
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn.functional as F
15
+
16
+ from langset import selection
17
+ from langset.modeling import LangSetModel
18
+ from langset.training_args import TrainingArguments
19
+
20
+
21
+ def _columns(dataset: Any) -> dict[str, list[Any]]:
22
+ if hasattr(dataset, "column_names"): # datasets.Dataset
23
+ return {c: list(dataset[c]) for c in dataset.column_names}
24
+ rows = list(dataset) # list[dict]
25
+ return {k: [r[k] for r in rows] for k in rows[0]}
26
+
27
+
28
+ class Trainer:
29
+ def __init__(self, model: LangSetModel, args: TrainingArguments, train_dataset: Any,
30
+ eval_dataset: Optional[Any] = None, column_mapping: Optional[dict[str, str]] = None,
31
+ label_columns: Optional[list[str]] = None) -> None:
32
+ self.model = model
33
+ self.args = args
34
+ cols = _columns(train_dataset)
35
+ cmap = column_mapping or {}
36
+ inv = {v: k for k, v in cmap.items()} # user-col -> canonical
37
+ get = lambda canon: cols[inv.get(canon, canon)] # noqa: E731
38
+ self.input_text = [str(x) for x in get("input_text")]
39
+ self.target_text = [str(x) for x in get("target_text")]
40
+ used = {inv.get("input_text", "input_text"), inv.get("target_text", "target_text")}
41
+ lc = label_columns if label_columns is not None else [c for c in cols if c not in used]
42
+ self.label_cols = {c: [str(x) for x in cols[c]] for c in lc}
43
+ if args.verbose:
44
+ print(f"[langset] {len(self.input_text)} rows | label columns (eval-only): {list(self.label_cols)}",
45
+ flush=True)
46
+
47
+ def train(self) -> LangSetModel:
48
+ a, m = self.args, self.model
49
+ dev = m.device
50
+ torch.manual_seed(a.seed)
51
+ rng = np.random.default_rng(a.seed)
52
+
53
+ # 1. bootstrap targets = bootstrap_encoder(target_text) (the seed geometry)
54
+ tgt_np = m.bootstrap_encoder.encode(self.target_text, normalize_embeddings=True,
55
+ convert_to_numpy=True, show_progress_bar=False).astype(np.float32)
56
+ tgt = torch.tensor(tgt_np, device=dev)
57
+ n = len(self.input_text)
58
+ perm = rng.permutation(n)
59
+ n_val = max(4, int(n * a.val_frac))
60
+ val_idx = perm[:n_val]
61
+ tr_idx = perm[n_val:]
62
+
63
+ tok = m.tokenizer
64
+ enc_in = tok(self.input_text, padding=True, truncation=True, max_length=a.max_len, return_tensors="pt")
65
+ ids = enc_in["input_ids"].to(dev)
66
+ mask = enc_in["attention_mask"].to(dev)
67
+
68
+ ema = tgt.clone() # EMA self-target (the "specialize" step)
69
+ opt = torch.optim.AdamW([p for p in m.parameters() if p.requires_grad], lr=a.lr)
70
+ run = None
71
+ if a.report_to == "wandb":
72
+ import wandb # type: ignore[import-untyped]
73
+ run = wandb.init(project=a.wandb_project, config=vars(a))
74
+
75
+ best_score, best_state, no_improve = -1e9, None, 0
76
+ for ep in range(a.epochs):
77
+ m.train()
78
+ order = tr_idx[rng.permutation(len(tr_idx))]
79
+ tot = nb = 0.0
80
+ for i in range(0, len(order), a.batch_size):
81
+ idx = torch.tensor(order[i:i + a.batch_size], device=dev)
82
+ pred = m(ids[idx], mask[idx])
83
+ target = ema[idx] if a.ema else tgt[idx]
84
+ logits = (pred @ target.t()) / a.tau # InfoNCE, in-batch negatives
85
+ loss = F.cross_entropy(logits, torch.arange(len(idx), device=dev))
86
+ if a.lam_anchor > 0: # pull toward the frozen bootstrap (0 = fully specialize)
87
+ loss = loss + a.lam_anchor * (1 - (pred * tgt[idx]).sum(1)).mean()
88
+ opt.zero_grad(); loss.backward(); opt.step()
89
+ if a.ema:
90
+ with torch.no_grad():
91
+ upd = a.ema_m * ema[idx] + (1 - a.ema_m) * pred.detach()
92
+ ema[idx] = F.normalize(upd, p=2, dim=-1)
93
+ tot += float(loss.detach()); nb += 1
94
+
95
+ if ep % a.eval_every:
96
+ continue
97
+ # 2. validate in the CURRENT geometry: input-view vs target-view co-location (never vs the seed)
98
+ vi = self.input_text and [self.input_text[j] for j in val_idx]
99
+ vt = [self.target_text[j] for j in val_idx]
100
+ emit_in = m.encode(vi, normalize_embeddings=True)
101
+ emit_tg = m.encode(vt, normalize_embeddings=True)
102
+ labels_val = {k: [v[j] for j in val_idx] for k, v in self.label_cols.items()}
103
+ metrics = selection.evaluate(emit_in, emit_tg, labels_val, tgt_np[val_idx], a.select)
104
+ if a.verbose:
105
+ extra = f" purity_mean={metrics.get('purity_mean'):.3f} beats={metrics.get('beats_bootstrap')}" \
106
+ if "purity_mean" in metrics else ""
107
+ print(f"ep{ep:02d} loss={tot/nb:.3f} mrr={metrics['mrr']:.3f} collapse={metrics['collapse']:.3f}"
108
+ f"{extra} score={metrics['score']:.3f} [{metrics['select_mode']}]", flush=True)
109
+ if run is not None:
110
+ run.log({"loss": tot / nb, **metrics, "epoch": ep})
111
+
112
+ if metrics["score"] > best_score:
113
+ best_score = metrics["score"]
114
+ best_state = {"head": {k: v.detach().cpu().clone() for k, v in m.head.state_dict().items()},
115
+ "lora": {k: v.detach().cpu().clone()
116
+ for k, v in m.backbone.state_dict().items() if "lora" in k}}
117
+ no_improve = 0
118
+ else:
119
+ no_improve += 1
120
+ if no_improve >= a.patience:
121
+ if a.verbose:
122
+ print(f"[langset] early stop at ep{ep} (best score {best_score:.3f})", flush=True)
123
+ break
124
+
125
+ if best_state is not None: # restore best
126
+ m.head.load_state_dict(best_state["head"])
127
+ m.backbone.load_state_dict(best_state["lora"], strict=False)
128
+ m.eval()
129
+ Path(a.output_dir).mkdir(parents=True, exist_ok=True)
130
+ m.save_pretrained(a.output_dir)
131
+ if run is not None:
132
+ run.finish()
133
+ if a.verbose:
134
+ print(f"[langset] done. best score={best_score:.3f} -> {a.output_dir}", flush=True)
135
+ return m
@@ -0,0 +1,34 @@
1
+ """Training configuration for langset. Defaults encode the lessons from the validated recipe:
2
+ EMA-specialize (ema_m + low anchor), select on geometry not loss, restore-best."""
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Literal, Optional
7
+
8
+
9
+ @dataclass
10
+ class TrainingArguments:
11
+ # optimization
12
+ epochs: int = 40
13
+ batch_size: int = 16
14
+ lr: float = 3e-4
15
+ tau: float = 0.07 # InfoNCE temperature
16
+ max_len: int = 512
17
+
18
+ # bootstrap -> specialize
19
+ ema: bool = True # EMA self-distillation target (the "specialize" step)
20
+ ema_m: float = 0.99 # EMA momentum (lower = faster drift off the bootstrap)
21
+ lam_anchor: float = 0.1 # cosine pull toward the FROZEN bootstrap target (0 = fully specialize)
22
+
23
+ # validation / early-stop (see selection.py)
24
+ val_frac: float = 0.2
25
+ eval_every: int = 1
26
+ patience: int = 6 # epochs without val improvement before stopping
27
+ select: Literal["auto", "retrieval", "purity", "loss"] = "auto" # auto = purity if labels else retrieval
28
+ seed: int = 0
29
+
30
+ # io / logging
31
+ output_dir: str = "langset-out"
32
+ report_to: Optional[str] = None # "wandb" or None
33
+ wandb_project: str = "langset"
34
+ verbose: bool = True
@@ -0,0 +1,172 @@
1
+ Metadata-Version: 2.4
2
+ Name: langset
3
+ Version: 0.1.0
4
+ Summary: Few-shot fine-tune an LLM to emit a latent into a bespoke, specialized geometry — and drop the result into SetFit as a Sentence-Transformer body.
5
+ Author: Stephen Solka
6
+ License: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: datasets>=2.15.0
10
+ Requires-Dist: numpy>=1.26
11
+ Requires-Dist: peft>=0.13.2
12
+ Requires-Dist: sentence-transformers>=3.0
13
+ Requires-Dist: torch>=2.2
14
+ Requires-Dist: transformers>=4.41
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest; extra == 'dev'
17
+ Requires-Dist: ruff; extra == 'dev'
18
+ Provides-Extra: setfit
19
+ Requires-Dist: scikit-learn; extra == 'setfit'
20
+ Requires-Dist: setfit>=1.1.0; extra == 'setfit'
21
+ Requires-Dist: torch<2.5,>=2.2; extra == 'setfit'
22
+ Requires-Dist: transformers<4.47,>=4.41; extra == 'setfit'
23
+ Provides-Extra: wandb
24
+ Requires-Dist: wandb>=0.18; extra == 'wandb'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # langset — read text, answer in a vector
28
+
29
+ **langset turns a language model into your own bespoke embedding space, few-shot.** Bolt a tiny vector head
30
+ onto a pretrained LLM, point it at a target geometry you define, and it learns to *read text and emit a latent*
31
+ into that space — using the LLM's world knowledge to do the work. From ~480 examples it builds a specialized
32
+ "how it sounds" geometry that **beats the encoder it was bootstrapped from on 4/5 held-out axes** — while the
33
+ *same architecture with a randomly-initialized backbone sits at chance*. That gap is the world knowledge, and
34
+ it's the whole point.
35
+
36
+ What makes langset different:
37
+
38
+ * 🎯 **Latent out, not a label.** You define the output space; the model answers in a *vector*, not a class.
39
+ The geometry can be anything a description can seed — "how it sounds", "how it behaves", "what it's like".
40
+ * 🧠 **World knowledge does the work.** It's a generative LLM, so it generalizes from *hundreds* of examples,
41
+ not millions. Swap in a random-init backbone and it barely moves off chance — the pretrained knowledge is
42
+ the engine.
43
+ * 🌱 **Bootstrap, then specialize.** Seed the target geometry from *any* off-the-shelf encoder (no contrastive
44
+ pairs, no labels), then an EMA self-target drifts it *off* that seed into your own task-shaped space — it
45
+ stops being "text similarity" and becomes its own thing (measurably: it leaves the seed's cone).
46
+ * 🔀 **Input-agnostic & non-circular.** Many input views can map to the same point, and you point the target at
47
+ a signal the input text can't regenerate — so it's not just distilling a text encoder.
48
+ * ✅ **Honest selection.** Optional per-row geometry labels are *eval-only* probes; langset early-stops on
49
+ their held-out kNN-purity with a collapse guard — never on the training loss (which collapse can game).
50
+
51
+ ## Install
52
+
53
+ ```bash
54
+ pip install langset
55
+ ```
56
+
57
+ ## Usage
58
+
59
+ A langset dataset is rows of `input_text` → `target_text` (+ optional eval-only geometry labels). You pick the
60
+ LLM backbone and the bootstrap encoder; langset trains the mapping and specializes the geometry.
61
+
62
+ ```python
63
+ from langset import LangSetModel, Trainer, TrainingArguments
64
+
65
+ rows = [ # a review SNIPPET (what you'll have at inference) -> a description that defines where it should land
66
+ {"input_text": "an hour-long track of detuned riffs that never break stride, moving at the pace of continental drift",
67
+ "target_text": "glacial detuned doom-metal, sludgy and hypnotic", "mood": "heavy"},
68
+ {"input_text": "chopped vocal ghosts drifting over vinyl crackle and the hiss of a city at 3am",
69
+ "target_text": "crackly nocturnal UK garage, pitched vocal ghosts", "mood": "calm"},
70
+ # ...
71
+ ]
72
+
73
+ model = LangSetModel.from_pretrained(
74
+ llm_model="HuggingFaceTB/SmolLM2-135M", # any HF causal LM (this is what the examples validate on)
75
+ bootstrap_model="sentence-transformers/all-MiniLM-L6-v2", # seeds the target geometry
76
+ )
77
+ Trainer(model, TrainingArguments(), train_dataset=rows).train() # 'mood' auto-detected as an eval-only label
78
+
79
+ z = model.encode(["a wall of downtuned fuzz that buries the vocals under sheer volume"]) # review snippet -> latent
80
+ print(z.shape) # (1, 384)
81
+ ```
82
+
83
+ See [`examples/sounds_like/`](examples/sounds_like/) for the full reference task (album review → "how it
84
+ sounds" latent, 481 albums): reproduced through this API at held-out kNN-purity **0.60**, beats-bootstrap
85
+ **4/5**.
86
+
87
+ ## How it works
88
+
89
+ 1. **Bootstrap.** Targets = the bootstrap encoder's embedding of `target_text`. No pairs, no labels.
90
+ 2. **Contrastive fit.** InfoNCE (in-batch negatives) trains the LLM emitter to hit its own target and separate
91
+ from others. A small cosine anchor optionally keeps it tethered to the seed.
92
+ 3. **Specialize.** An EMA self-target drifts the geometry off the seed into the model's own arrangement (set
93
+ `lam_anchor` low to let it go). Emergent structure falls out — never trained, never labeled.
94
+
95
+ ## Validation / early-stop (the part that bites)
96
+
97
+ Two traps langset refuses to fall into:
98
+
99
+ - **Never select on training loss** — InfoNCE + EMA can minimize it by *collapsing* the geometry.
100
+ - **Never score retrieval against the frozen bootstrap targets** — the model specializes *away* from them.
101
+
102
+ So it selects on held-out geometry in the *current* space: input-view↔target-view retrieval + a **collapse
103
+ guard** by default; **held-out kNN-purity (+ beats-bootstrap)** when rows carry geometry labels. Early-stop =
104
+ patience + restore-best.
105
+
106
+ ## Dataset contract
107
+
108
+ | column | meaning |
109
+ |---|---|
110
+ | `input_text` | what you'll have at inference (a name, query, review) |
111
+ | `target_text` | a description of the same item defining where it lands (seeds the geometry) |
112
+ | *anything else* | optional **eval-only** geometry labels (kNN-purity at validation; never trained on) |
113
+
114
+ `Trainer` accepts a `datasets.Dataset` or `list[dict]`; use `column_mapping` to rename your columns.
115
+
116
+ ## Using with SetFit
117
+
118
+ The name is the chain: **lang·set·fit** — a *language* model emits into the *set* geometry (langset, usable on
119
+ its own), which then *fit*s a classifier. `model.as_sentence_transformer()` is a drop-in
120
+ [SetFit](https://github.com/huggingface/setfit) `model_body`, so you can train a few-shot classifier directly
121
+ on the specialized geometry. On the sounds-like example, a genre classifier on the **langset body beats one on
122
+ raw MiniLM, 0.240 vs 0.205**.
123
+
124
+ ### When to reach for which
125
+
126
+ The clean distinction: **SetFit answers with a *label*; langset answers with a *latent*.** SetFit is a few-shot
127
+ *classifier*; langset is a few-shot *bespoke embedding space* — classification is just one thing you can do
128
+ downstream of a latent.
129
+
130
+ | | reach for **SetFit** | reach for **langset** |
131
+ |---|---|---|
132
+ | your answer is | a **label** (fixed classes) | a **point in a space** — retrieval, "find similar", ranking, clustering |
133
+ | you define the target by | enumerating classes | a **description** of the geometry ("how it sounds") |
134
+ | your input | text to classify | text *or an identifier* (a name) — leans on the LLM's world knowledge |
135
+ | plain few-shot classification | ✅ simpler, faster, proven | not its job |
136
+
137
+ - **Use SetFit alone** for plain few-shot classification — it directly optimizes class separation; you won't
138
+ beat it by bolting on langset.
139
+ - **Use langset** when the answer is a *geometry, not a label* (you'll retrieve / rank / cluster in it).
140
+ - **Use langset → SetFit** when a task-shaped body helps the classifier (demo: genre 0.240 vs 0.205 — modest,
141
+ so treat it as "plausibly helps", not a slam-dunk).
142
+
143
+ ```bash
144
+ pip install "langset[setfit]" # pins the verified composition window (below)
145
+ ```
146
+ ```python
147
+ from sklearn.linear_model import LogisticRegression
148
+ from setfit import SetFitModel
149
+
150
+ clf = SetFitModel(model_body=langset_model.as_sentence_transformer(),
151
+ model_head=LogisticRegression(max_iter=2000), # direct construction needs an explicit head
152
+ labels=[...])
153
+ clf.fit(x_train, y_train, num_epochs=1) # frozen body + head — the robust path
154
+ clf.predict(["..."])
155
+ ```
156
+
157
+ **Dependency alignment.** SetFit's pins are loose, so versions matter:
158
+
159
+ | install | transformers / torch | Python | use |
160
+ |---|---|---|---|
161
+ | `langset` | latest (≥4.41) | 3.10+ | modern backbones incl. **Qwen3**; no SetFit |
162
+ | `langset[setfit]` | **4.46.x / <2.5** | **3.10–3.12** | verified SetFit composition |
163
+
164
+ SetFit imports `transformers.training_args.default_logdir` (removed after 4.46), and 4.46 + torch≥2.5 trips a
165
+ `torch.distributed.tensor` bug — hence the cap. Use the frozen-body `SetFitModel.fit`/`predict` path above; the
166
+ full `setfit.Trainer` (fine-tunes the body) is fragile in this window. Qwen3 + SetFit can't share one env until
167
+ SetFit drops that import.
168
+
169
+ ## Status
170
+
171
+ v0.1 — the core engine, validated on a real task (album review → "how it sounds" latent), with a downstream
172
+ classifier composition (see above). No trust/hallucination layer yet (intentionally out of v1). Apache-2.0.
@@ -0,0 +1,11 @@
1
+ langset/__init__.py,sha256=HTWJ-j7EQgzC16xXQwbaSC1iPS6cESVfEYWE24Ilcrs,428
2
+ langset/data.py,sha256=8RZ-_BBRD9J-M3PK4K90i7JgYZrcyhs5ZB22cpK-nL0,1370
3
+ langset/modeling.py,sha256=NoT4smQBBhpC5eO9Cb0UEriXHTC2WKo94c4Da6s3Bq8,8463
4
+ langset/selection.py,sha256=afiZijbATbvIHPNUUU72Kx6TZYFfiXxRJj8FqcUgj-E,3691
5
+ langset/st_module.py,sha256=8wf7xlqh1n8kpN_7AyzcdwfEMiQ24PxqjmBSGeTt2X0,2621
6
+ langset/trainer.py,sha256=Yd6ba1s6mCQLmCtvc0lTBbusMTJ0Jid8F5l_QsAzVQs,6816
7
+ langset/training_args.py,sha256=08Cba4YROFUR-fheWPl-gaPUu358tBJp4liJlILeNE4,1331
8
+ langset-0.1.0.dist-info/METADATA,sha256=MEl_o7lsEbL5aDA9wPn1BZ7pKu3xrTMku5Pw54mIirc,8948
9
+ langset-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
10
+ langset-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
11
+ langset-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,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.