Download dflow/prompt_emphasis.py from data-archetype/dflow_2b: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/data-archetype/dflow_2b/resolve/main/dflow/prompt_emphasis.py
- Command line
-
hf download hf://data-archetype/dflow_2b/dflow/prompt_emphasis.py
-
curl -L -o prompt_emphasis.py https://huggingface.co/data-archetype/dflow_2b/resolve/main/dflow/prompt_emphasis.py
10.2 kB
| r"""Prompt emphasis: ``(phrase:weight)`` markup applied through attention. | |
| Markup (the grammar of the ComfyUI ``MOSSImagePromptWeight`` node): | |
| - the prompt is NFC-normalized first; | |
| - a balanced ``(...)`` group whose text after its last colon is a number | |
| (``2``, ``.5``, ``-1``) weights the phrase before that colon; the phrase may | |
| hold colons, and groups nest (an inner weight overrides its outer group); | |
| - any other group, and an unmatched parenthesis, stays literal text; | |
| - ``\(`` and ``\)`` are literal parentheses. | |
| Weights reach the model per token: a token takes the weight of the last group | |
| whose phrase its characters overlap; weight 1 changes nothing. | |
| - Weight > 0: an additive bias on the token's attention key logits, | |
| ``strength * log(w)`` (``LOG``: the token's share of attention is | |
| multiplied by ``w``) or ``strength * 2 * (w - 1)`` (``LINEAR``). | |
| - Weight <= 0: the token's attention value is scaled by | |
| ``1 + strength * (w - 1)`` (0 mutes it, -1 subtracts it). | |
| The bias and scale act in every joint attention of the weighted prompt's | |
| forward passes and, with ``EmphasisSettings.encoder``, inside the text | |
| encoder's self-attention too. JSON layout prompts are never parsed. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import re | |
| import unicodedata | |
| from collections.abc import Sequence | |
| from dataclasses import dataclass | |
| from enum import StrEnum | |
| __all__ = [ | |
| "EmphasisMapping", | |
| "EmphasisSettings", | |
| "ParsedPrompt", | |
| "TokenEmphasis", | |
| "WeightedTerm", | |
| "parse_prompt_weights", | |
| "token_emphasis", | |
| "token_weights", | |
| ] | |
| # A group's weight: the text after its last colon, matched in full. | |
| _WEIGHT = re.compile(r"-?\d*\.?\d+") | |
| # One-character stand-ins for escaped parentheses (positions do not move). | |
| _ESCAPED = {"(": "\x01", ")": "\x02"} | |
| _UNESCAPED = {value: key for key, value in _ESCAPED.items()} | |
| _NEUTRAL_WEIGHT = 1.0 | |
| _NEUTRAL_BIAS = 0.0 | |
| _NEUTRAL_SCALE = 1.0 | |
| class EmphasisMapping(StrEnum): | |
| """How a positive weight becomes an attention-logit bias. | |
| LOG: ``log(w)``; ``(x:2)`` gets exactly twice the attention mass. | |
| LINEAR: ``2 * (w - 1)``; ``(x:2)`` gets about 7 times the mass. | |
| """ | |
| LOG = "log" | |
| LINEAR = "linear" | |
| class EmphasisSettings: | |
| """Prompt-emphasis settings. | |
| The defaults are the ComfyUI ``MOSSImagePromptWeight`` node's: ``LINEAR`` | |
| mapping, strength 1, encoder weighting on. | |
| Attributes: | |
| mapping: Positive-weight to logit-bias mapping. | |
| strength: Multiplier on every bias and value-scale offset. | |
| encoder: Also apply the weights inside the text encoder. | |
| Raises: | |
| ValueError: If ``strength`` is negative or not finite. | |
| """ | |
| mapping: EmphasisMapping = EmphasisMapping.LINEAR | |
| strength: float = 1.0 | |
| encoder: bool = True | |
| def __post_init__(self) -> None: | |
| """Validate the strength.""" | |
| if not math.isfinite(self.strength) or self.strength < 0.0: | |
| raise ValueError(f"strength must be finite and >= 0, got {self.strength}.") | |
| def key_bias(self, weight: float) -> float: | |
| """Return the key-logit bias of a token with weight > 0.""" | |
| match self.mapping: | |
| case EmphasisMapping.LOG: | |
| return self.strength * math.log(weight) | |
| case EmphasisMapping.LINEAR: | |
| return self.strength * 2.0 * (weight - 1.0) | |
| case _ as unreachable: | |
| raise ValueError(f"Unsupported emphasis mapping: {unreachable}") | |
| def value_scale(self, weight: float) -> float: | |
| """Return the value multiplier of a token with weight <= 0.""" | |
| return 1.0 + self.strength * (weight - 1.0) | |
| class WeightedTerm: | |
| """One weighted group of a prompt. | |
| Attributes: | |
| start, end: The phrase in the clean text, surrounding spaces excluded. | |
| weight: Its weight (any real number; 1 changes nothing). | |
| raw_start, raw_end: The whole ``(...:w)`` group in the NFC-normalized | |
| prompt as typed (for highlighting it). | |
| """ | |
| start: int | |
| end: int | |
| weight: float | |
| raw_start: int | |
| raw_end: int | |
| class ParsedPrompt: | |
| """A prompt with its emphasis markup removed. | |
| Attributes: | |
| clean_text: What the text encoder reads. | |
| terms: Weighted groups, each outer group before the groups nested in | |
| it (a later term overrides an earlier one on shared tokens). | |
| """ | |
| clean_text: str | |
| terms: tuple[WeightedTerm, ...] | |
| def parse_prompt_weights(text: str) -> ParsedPrompt: | |
| """Parse ``(phrase:weight)`` markup (grammar in the module docstring).""" | |
| normalized = unicodedata.normalize("NFC", text) | |
| escaped, raw_at = _escape(normalized) | |
| terms: list[WeightedTerm | None] = [] | |
| clean = _strip_weights(escaped, 0, len(escaped), terms=terms, base=0, raw_at=raw_at) | |
| return ParsedPrompt( | |
| clean_text="".join(_UNESCAPED.get(char, char) for char in clean), | |
| terms=tuple(term for term in terms if term is not None), | |
| ) | |
| def _escape(text: str) -> tuple[str, list[int]]: | |
| """Replace ``\\(`` / ``\\)`` by one-character stand-ins; return the raw | |
| index of each character (plus the end).""" | |
| out: list[str] = [] | |
| raw_at: list[int] = [] | |
| pos = 0 | |
| while pos < len(text): | |
| pair = text[pos : pos + 2] | |
| if len(pair) == 2 and pair[0] == "\\" and pair[1] in _ESCAPED: | |
| out.append(_ESCAPED[pair[1]]) | |
| raw_at.append(pos) | |
| pos += 2 | |
| else: | |
| out.append(text[pos]) | |
| raw_at.append(pos) | |
| pos += 1 | |
| raw_at.append(len(text)) | |
| return "".join(out), raw_at | |
| def _groups(text: str, lo: int, hi: int) -> list[tuple[int, int]]: | |
| """Split ``text[lo:hi]`` into text runs and balanced ``(...)`` groups.""" | |
| out: list[tuple[int, int]] = [] | |
| depth, start = 0, lo | |
| for pos in range(lo, hi): | |
| if text[pos] == "(": | |
| if depth == 0: | |
| out.append((start, pos)) | |
| start = pos | |
| depth += 1 | |
| elif text[pos] == ")" and depth: | |
| depth -= 1 | |
| if depth == 0: | |
| out.append((start, pos + 1)) | |
| start = pos + 1 | |
| if depth: | |
| # An unmatched "(" stays text; what follows it is split again. | |
| return [*out, (start, start + 1), *_groups(text, start + 1, hi)] | |
| return [*out, (start, hi)] | |
| def _strip_weights( | |
| text: str, | |
| lo: int, | |
| hi: int, | |
| *, | |
| terms: list[WeightedTerm | None], | |
| base: int, | |
| raw_at: Sequence[int], | |
| ) -> str: | |
| """Return ``text[lo:hi]`` without weight markup, recording the terms. | |
| ``base`` is where the returned text starts in the whole clean text. | |
| """ | |
| out = "" | |
| for a, b in _groups(text, lo, hi): | |
| if b - a < 2 or text[a] != "(" or text[b - 1] != ")": | |
| out += text[a:b] | |
| continue | |
| colon = text.rfind(":", a + 1, b - 1) | |
| weight = text[colon + 1 : b - 1].strip() if colon >= 0 else "" | |
| if ( | |
| colon < 0 | |
| or text[a + 1 : colon].strip() == "" | |
| or _WEIGHT.fullmatch(weight) is None | |
| ): | |
| inner = _strip_weights( | |
| text, a + 1, b - 1, terms=terms, base=base + len(out) + 1, raw_at=raw_at | |
| ) | |
| out += "(" + inner + ")" | |
| continue | |
| index = len(terms) | |
| terms.append(None) # the outer group first, so nested groups override it | |
| start = base + len(out) | |
| phrase = _strip_weights( | |
| text, a + 1, colon, terms=terms, base=start, raw_at=raw_at | |
| ) | |
| terms[index] = WeightedTerm( | |
| start=start + len(phrase) - len(phrase.lstrip()), | |
| end=start + len(phrase.rstrip()), | |
| weight=float(weight), | |
| raw_start=raw_at[a], | |
| raw_end=raw_at[b - 1] + 1, | |
| ) | |
| out += phrase | |
| return out | |
| def token_weights( | |
| terms: Sequence[WeightedTerm], offsets: Sequence[tuple[int, int]] | |
| ) -> list[float]: | |
| """Return each token's weight: that of the last term its span overlaps. | |
| Args: | |
| terms: The prompt's weighted terms, outer groups first. | |
| offsets: Per token, its ``(start, end)`` span in the clean text | |
| (``(0, 0)`` for special tokens, which never overlap a term). | |
| """ | |
| weights = [_NEUTRAL_WEIGHT] * len(offsets) | |
| for term in terms: | |
| for pos, (lo, hi) in enumerate(offsets): | |
| if lo < term.end and hi > term.start: | |
| weights[pos] = term.weight | |
| return weights | |
| class TokenEmphasis: | |
| """Per-token attention bias and value scale of one prompt. | |
| Attributes: | |
| key_bias: Additive key-logit bias per token (0: unchanged). | |
| value_scale: Value multiplier per token (1: unchanged). | |
| """ | |
| key_bias: tuple[float, ...] | |
| value_scale: tuple[float, ...] | |
| def has_key_bias(self) -> bool: | |
| """Whether any token's key bias differs from 0.""" | |
| return any(value != _NEUTRAL_BIAS for value in self.key_bias) | |
| def has_value_scale(self) -> bool: | |
| """Whether any token's value scale differs from 1.""" | |
| return any(value != _NEUTRAL_SCALE for value in self.value_scale) | |
| def token_emphasis( | |
| parsed: ParsedPrompt, | |
| offsets: Sequence[tuple[int, int]], | |
| settings: EmphasisSettings, | |
| ) -> TokenEmphasis | None: | |
| """Map a parsed prompt's weights onto its tokens. | |
| Args: | |
| parsed: The parsed prompt. | |
| offsets: Per token of ``parsed.clean_text``, its character span. | |
| settings: The mapping and strength. | |
| Returns: | |
| The token bias and scale, or None when no token is weighted. | |
| """ | |
| if not parsed.terms: | |
| return None | |
| weights = token_weights(parsed.terms, offsets) | |
| if all(weight == _NEUTRAL_WEIGHT for weight in weights): | |
| return None | |
| return TokenEmphasis( | |
| key_bias=tuple( | |
| settings.key_bias(w) if w > 0.0 and w != _NEUTRAL_WEIGHT else _NEUTRAL_BIAS | |
| for w in weights | |
| ), | |
| value_scale=tuple( | |
| settings.value_scale(w) if w <= 0.0 else _NEUTRAL_SCALE for w in weights | |
| ), | |
| ) | |