Search & ranking

Separate Category Retrieval from the Final Classification

Compare k=1,3,5 on the same name-masked activities. More candidates leave determinate coverage unchanged here, help one mixed case and still permit unsupported assignments.

FinanceIndependent technical study

Source case: Ramp. The article separates the published design from the data, methods and observations in this local experiment.

A candidate can be relevant without establishing the primary activity

An analyst sees a business that prepares drinks and ships packaged beans. Both activities are real in the supplied observation, but their relative importance is missing. Returning the coffee-sales category may look well supported because the quoted phrase exists. It still answers a question the evidence did not settle: which activity should determine the primary assignment?

The improvement worth seeking is not simply another correct label on an easy example. A selector must interpret neighbouring meanings and recognise when the available evidence cannot support any single leaf. This study makes candidate coverage, selection and review separate observations.

Read the published system before building a substitute

Ramp’s January 2025 account describes replacing inconsistent industry mappings with NAICS. Embedding retrieval supplies recommendations; two LLM prompts narrow a broad list before examining richer context. ClickHouse supports similarity retrieval and Kafka retains intermediates. Evaluation separates coverage from hierarchy-sensitive final scoring. Its output guard checks valid codes, allowing correct predictions outside the recommendations. Published engineering account

Study reconstruction: embeddings, retrieval, broad then detailed selection, and a valid-code check, with intermediate logging.Open full-size diagram (opens in a new tab)

Study reconstruction of the published design, not an original Ramp image or the local experiment.

Design reference: Ramp Builders · 15 January 2025

My interpretation is that the two prompts allocate context. A broad first stage can avoid spending detailed context on every definition; a narrower stage can inspect distinctions among plausible neighbours. It also introduces another place to discard a correct candidate. That architecture needs an end-to-end justification rather than an assumption that more model calls improve classification.

The implementation below uses one prompt per observation and candidate size. It does not evaluate that two-prompt design, dense retrieval or a NAICS hierarchy.

Measure the part of the pipeline that can actually fail

For this candidate-only service, correct leaf assignment decomposes as:

P(correct) = P(correct leaf retrieved) × P(correct selection | correct leaf retrieved)

This is a probability identity under the declared restriction, not an independence assumption. The published code-validity guard described above is a different boundary. Here an unretrieved leaf cannot pass the host contract, even if a model proposes a plausible external answer.

The new corpus is shared with the Square input study. Sixteen public-company observations train its CPU models; twelve entity-disjoint diagnostics supply this study’s queries. Eight diagnostics paraphrase selected official public facts and four are authored counterexamples. A separate model agent reviewed descriptions without names or predictions before fitting and inference. Its frozen references contain eight determinate leaves and four REVIEW cases. They are development references, not human industry annotations or complete company classifications.

TF-IDF indexes eight positive definitions in four parent families. It uses smoothed IDF, sublinear term frequency and cosine similarity. Exclusions and parent identifiers accompany candidates into the selector but are not part of the retrieval index. The query also omits company names and URLs, reducing the opportunity to replace missing descriptive evidence with familiar-brand knowledge.

Actual retrieval over positive definitions, with a fixed kPython17 lines
def retrieve(text, categories, k):
    """TF-IDF cosine over positive definitions; exclusions are selection context."""
    documents = [tokens(row["label"] + " " + row["description"]) for row in categories]
    df = Counter(term for doc in documents for term in set(doc))
    idf = {term: math.log((len(documents) + 1) / (count + 1)) + 1 for term, count in df.items()}
    def vector(words):
        return {term: (1 + math.log(count)) * idf[term]
                for term, count in Counter(words).items() if term in idf}
    query = vector(tokens(text))
    qnorm = math.sqrt(sum(x * x for x in query.values()))
    ranked = []
    for row, document in zip(categories, documents):
        vec = vector(document)
        norm = math.sqrt(sum(x * x for x in vec.values()))
        dot = sum(weight * vec.get(term, 0) for term, weight in query.items())
        ranked.append({"category": row["id"], "score": dot / (qnorm * norm) if qnorm and norm else 0., "definition": row})
    return sorted(ranked, key=lambda row: (-row["score"], row["category"]))[:k]

A larger k can improve coverage while adding near neighbours, distractors and context. This sample makes a useful negative finding: top-one already covers and matches all eight determinate references. Increasing k cannot improve that part of the result. No text or category definition was changed after seeing this outcome to manufacture retrieval headroom.

Keep the observation fixed while changing its candidate context

Each name-masked diagnostic is submitted at k=1,3,5 with the same model, instruction, schema family and generation options. Only the retrieved candidate set changes. The model may select a supplied leaf or return REVIEW; a selected leaf needs one exact, unique quotation. References never enter its request.

Candidate sizeCoverageConditional selectionCorrect REVIEWForced leaf on REVIEWReported prompt counter total
18 / 88 / 81 / 43 / 42,747
38 / 88 / 82 / 42 / 44,465
58 / 88 / 82 / 42 / 46,201

Each row represents twelve compatible-runtime generations. Conditional selection retains every covered determinate call in its denominator, including a failed output contract if one occurred. All thirty-six responses pass the declared shape and quote checks in this trial. The API counters are retained literally, with cache counters available separately; these totals are not invoices or a latency ranking.

All determinate model selections also match their parent references. That adds no demonstrated hierarchy benefit because the leaves are already correct. C2 has no determinate diagnostic example: the reviewer kept the apparently relevant production/fulfillment observation unresolved. Reporting eight available classes must not imply that all eight have positive evaluation coverage.

At k=3, a mixed facial-treatment and skincare-sales observation changes from a forced product label to REVIEW. At k=5 the disposition remains unchanged while the reported prompt counter increases. The result supports keeping three as the next development candidate size, rather than paying for unexplained extra breadth. It does not establish a general optimum.

A valid quote can preserve the wrong inference

Two retained failures explain why the selector remains unsuitable for automatic assignment.

Generic production is not printing-specific evidence. One observation describes custom products, physical supply and order fulfillment, without specifying printing or the relevant merchandise. The reviewer retained REVIEW under this task’s policy. At all three sizes, Qwen selects C2 and quotes the genuine production/fulfillment statement. Its interpretation expands a general activity into a more specific leaf. This is an evidence-policy failure, not proof that the real company belongs to a different industry.

One supported activity does not establish dominance. The mixed coffee example explicitly includes prepared drinks and shipped beans, with no primary operation established. Every candidate size selects packaged-coffee sales and quotes the shipping activity. The quote supports the existence of that activity. It does not establish that it should govern the assignment.

The host can prove candidate membership and locate text; it cannot establish those semantic conclusions from a string match. Even correct REVIEW dispositions need their reasons inspected: a good category decision is not a guarantee that every sentence of its explanation is justified.

This is where a model comparison differs from a schema demonstration. The deterministic top-one path forces a leaf on all four review references. The selector correctly withholds some assignments, but still forces two at k=3 and k=5. That is a narrower benefit and a remaining failure surface, rather than a blanket quality improvement.

Inspect all thirty-six saved proposals and their separate reference decisions

Recorded experiment

What the experiment actually shows

The separately authorized compatible-runtime trial compares twelve name-masked observations at k=1,3,5. Its original responses are retained; the earlier 36 HTTP500 attempts produced no semantic observations.

Data and comparison boundary

Methods compared

TF-IDF top one
A deterministic retrieval baseline over eight positive definitions.
Candidate-only Qwen selector
The same local model sees k definitions, their exclusions and a literal-quote/review contract. There is one prompt per observation/k pair.

Recorded findings

k=1
coverage 8/8; selection 8/8

Conditional selection 8/8; correct review 1/4; invalid calls 0; API prompt_eval total 2747.

k=3
coverage 8/8; selection 8/8

Conditional selection 8/8; correct review 2/4; invalid calls 0; API prompt_eval total 4465.

k=5
coverage 8/8; selection 8/8

Conditional selection 8/8; correct review 2/4; invalid calls 0; API prompt_eval total 6201.

Inspect a recorded example

D01 · k=1
Input

Customers choose seasonal ingredients for a meal. This location offers salads, warm bowls and wraps. Guests can order food for pickup.

Baseline output

Retrieved order: F1

Candidate output

{ "status": "bound", "issue": null, "candidate": { "category": "F1", "quote": "This location offers salads, warm bowls and wraps.", "reason": "The observation explicitly lists salads, warm bowls, and wraps — all items covered under 'Prepared food and drink'." }, "semantic_entailment_verified": false }

These are saved results. Switching examples runs no model or external service.

Limits of this experiment

  • References are a separate model agent's pre-prediction review, not human industry labels or official company codes.
  • No broader-class fallback is released as a correct leaf. C2 has no determinate diagnostic reference in this sample.
  • Three sequential candidate sizes on one runtime do not establish money saved or latency improvement.
Inspect the recorded provenance
{
  "calls_sha256": "28a8ec63cffb3fb0aa65b37ff0c2c59f5c49e148a7dda8adb4c339b026cdd584",
  "corpus_sha256": "acd2d0abbc8001114d56dd2de69535a01006df455666f17ea746fc8d234a4b26",
  "cpu_code_sha256": "e43da0368fb32d502c85c881d064c342cf685284c5bfc4e93b1e2e1c4d8fdf44",
  "evaluation_code_sha256": "b74376be594e4e39eae52f87c10637ec49fc3d45c982cc7a197a5cc447d2ed9a",
  "initial_infrastructure_trial": {
    "file": "calls.json",
    "http_requests": 36,
    "model": {
      "details": {
        "families": [
          "qwen3vl",
          "clip"
        ],
        "family": "qwen3vl",
        "format": "gguf",
        "parameter_size": "4.0B",
        "parent_model": "",
        "quantization_level": "Q4_K_M"
      },
      "digest": "8708ab6acc5eed95c57d3d4b68c08f85eb197840827c097c7d9ed49f2a030c6e",
      "model": "qwen3-vl:4b-instruct-q4_K_M",
      "modified_at": "2026-11-25T21:56:46.663784614+01:00",
      "name": "qwen3-vl:4b-instruct-q4_K_M",
      "size": 3337226771
    },
    "reason": "Runtime 0.17.7 runner failures; the separately recorded compatible trial also reports a different API model identity. Identical request bodies do not make this a controlled runtime-only comparison.",
    "runtime": {
      "version": "0.17.7"
    },
    "sha256": "6a3cade5caa2e40d3c881878ca0e08ef67062bf711f2716fc8038dbea9ebdaeb",
    "successful_generations": 0
  },
  "model": {
    "capabilities": [
      "completion",
      "vision",
      "tools"
    ],
    "details": {
      "context_length": 262144,
      "embedding_length": 2560,
      "families": [
        "qwen3vl",
        "clip"
      ],
      "family": "qwen3vl",
      "format": "gguf",
      "parameter_size": "4.0B",
      "parent_model": "dhiltgen/qwen3-vl:4b-instruct-q4_K_M-llamacpp",
      "quantization_level": "Q4_K_M",
      "runner": "llamacpp"
    },
    "digest": "84f7ed8042fa7cdbd902f7dcb7d0370e032095047cc3244179f263b77b5bc318",
    "model": "qwen3-vl:4b-instruct-q4_K_M",
    "modified_at": "2026-11-25T21:56:46.65935228+01:00",
    "name": "qwen3-vl:4b-instruct-q4_K_M",
    "size": 3337225651
  },
  "model_counts_sha256": "66dfd8df9a4ffd1560a1b6cac41b912f5573c38261c1b289fc069804353a3310",
  "recording_basis": {
    "blind-review.json": "cb7640961bf72159202cd0a0ce3ff7157f66d97cd5ba811fb539e062f434fcdf",
    "core.py": "e43da0368fb32d502c85c881d064c342cf685284c5bfc4e93b1e2e1c4d8fdf44",
    "corpus.json": "acd2d0abbc8001114d56dd2de69535a01006df455666f17ea746fc8d234a4b26",
    "reference.json": "2f2e816462abeb8b10d87c414a7e2433b22215c8c42295a6d1a5df6f11e184ab",
    "run_compatible_model.py": "26f6988e7fdf106aa92a544e90a3172f29348aba557caa59120f62786b26e070",
    "run_model.py": "3a91a34d5e3f3280e0ba5eccc8122bf0c756f8cfc47cd4712d1ea671b0b74f92",
    "taxonomy.json": "5971417e205c466d5de873f3616498cb5271e67ed3333c9d95e02568bf2e1737"
  },
  "reference_sha256": "2f2e816462abeb8b10d87c414a7e2433b22215c8c42295a6d1a5df6f11e184ab",
  "reviewer": "Second model agent, separate from the source/data author; not a human industry annotation or independent population test",
  "runtime": {
    "version": "0.40.18"
  },
  "selected_trial": "calls-compatible.json",
  "source_manifest_sha256": "81a769e36044ad32931d66c78a2a863846d5131082af485dbb0ad85d54015740",
  "taxonomy_sha256": "5971417e205c466d5de873f3616498cb5271e67ed3333c9d95e02568bf2e1737",
  "token_note": "API counters are retained literally, including cache counters. These are not invoices, a latency benchmark or a complete provider-cost comparison."
}
Literal response binding does not establish semantic entailmentPython18 lines
def bind_selection(text, candidates, response):
    if not isinstance(response, dict) or response.get("done") is not True or response.get("done_reason") == "length":
        return {"status": "invalid", "issue": "incomplete_response", "candidate": None}
    try:
        candidate = json.loads(response["message"]["content"])
    except (KeyError, TypeError, json.JSONDecodeError):
        return {"status": "invalid", "issue": "invalid_json", "candidate": None}
    if (not isinstance(candidate, dict) or set(candidate) != {"category", "quote", "reason"}
            or type(candidate["category"]) is not str or type(candidate["reason"]) is not str or not candidate["reason"].strip()):
        return {"status": "invalid", "issue": "schema", "candidate": candidate}
    if candidate["category"] == "REVIEW":
        issue = None if candidate["quote"] is None else "review_quote_not_null"
    else:
        quote = candidate["quote"]
        issue = ("category_not_retrieved" if candidate["category"] not in {c["category"] for c in candidates} else
            "quote_not_uniquely_bound" if type(quote) is not str or not quote.strip() or text.count(quote) != 1 else None)
    return {"status": "bound" if issue is None else "invalid", "issue": issue,
            "candidate": candidate, "semantic_entailment_verified": False}

Decide where language understanding earns its place

For a larger taxonomy, I would examine candidate coverage and conditional selection separately by neighbouring category pair. A broader-family match is useful diagnosis but does not erase a wrong leaf. Query-field weighting would also deserve its own comparison: names, descriptions and behavioural evidence have different coverage and provenance. Dense representations might recover unfamiliar phrasing but blur nearby activities; neither effect was measured here.

For this data, the next boundary is review quality. Missing descriptions, mixed activities and insufficient specificity should not become forced labels merely because retrieval supplied a plausible candidate. A human-reviewed slice and a declared primary-activity policy would be more valuable than adding another model stage to an already complete retrieval result.

The adoption decision therefore remains limited: keep the inspectable retrieval baseline, retain the selector as a review experiment, and decline automatic assignment. The companion’s cleaned-context gain does not imply this selector is beneficial, just as this selector’s review behaviour does not validate the companion’s input policy. They answer different questions using one disclosed data foundation.

Trial provenance, earlier experiment and offline reproduction

The first new trial returned thirty-six HTTP500 responses and no generated proposals. Its request bodies remain untouched as infrastructure evidence. The separately authorized compatible trial submitted identical payloads and recorded thirty-six HTTP200 generations without semantic prompt changes or output repair. It also reported different runtime and model identities, so this is not a controlled runtime-only comparison. Only that trial supplies the selection results above; infrastructure failures are not a zero-percent model-quality result.

The earlier fictional engineering-lab/classification experiment remains unchanged. The new engineering-lab/merchant-study directory has an explicit portable allowlist, source URLs, pre-prediction review hashes, both raw trial ledgers and exact code exports. Run python3 run.py, python3 verify_recording.py and python3 smoke.py to reproduce offline. These commands do not call a model. The actual API model identity and runtime version are preserved rather than inferred from a legacy cache filename.