Run this model with HF Jobs

Run litert-community/EdgeCoder-Multilingual-61M on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/litert-community/EdgeCoder-Multilingual-61M. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/litert-community/EdgeCoder-Multilingual-61M on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
File size: 3,709 Bytes
c4546e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""Run the FP32 EdgeCoder encode_128 LiteRT graph on the CPU.

Requires ai-edge-litert, numpy, and transformers.
Place the graph beside this script or pass its path with --model.
Use --tokenizer with a local copy of the pinned tokenizer for offline runs.
"""

import argparse
from pathlib import Path

import numpy as np


TOKENIZER_REPO = "knowledgator/EdgeCoder-Multilingual-61M"
TOKENIZER_REVISION = "d2b4066c768e16b763c0693f6ad474c520ce64e3"
GRAPH_NAME = "edgecoder_encode_128_fp32.tflite"
SEQUENCE_LENGTH = 128


def load_tokenizer(source):
    from transformers import AutoTokenizer

    return AutoTokenizer.from_pretrained(
        source,
        revision=TOKENIZER_REVISION if source == TOKENIZER_REPO else None,
        local_files_only=Path(source).is_dir(),
        trust_remote_code=False,
        use_fast=True,
        padding_side="right",
        truncation_side="right",
    )


def open_encoder(model_path):
    from ai_edge_litert.interpreter import Interpreter

    interpreter = Interpreter(model_path=str(model_path), num_threads=1)
    return interpreter.get_signature_runner("encode_128")


def encode_text(encoder, tokenizer, text):
    tokens = tokenizer(
        text,
        padding="max_length",
        truncation=True,
        max_length=SEQUENCE_LENGTH,
        return_attention_mask=True,
        return_token_type_ids=False,
        return_tensors="np",
    )
    inputs = {
        name: tokens[name].astype(np.int32, copy=False)
        for name in ("input_ids", "attention_mask")
    }
    return encoder(**inputs)["last_hidden_state"], inputs


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("text", help="first text to encode")
    parser.add_argument("second_text", nargs="?", help="optional second text to encode")
    parser.add_argument(
        "--model", type=Path, default=Path(__file__).absolute().with_name(GRAPH_NAME),
        help="path to the FP32 LiteRT graph (default: beside this script)",
    )
    parser.add_argument(
        "--tokenizer", default=TOKENIZER_REPO,
        help="tokenizer directory or Hugging Face repository (default: the author's pinned revision)",
    )
    args = parser.parse_args()
    if not args.model.is_file():
        parser.error(f"model file not found: {args.model}")

    tokenizer = load_tokenizer(args.tokenizer)
    encoder = open_encoder(args.model)
    texts = (args.text,) if args.second_text is None else (args.text, args.second_text)
    pooled_vectors = []
    norms = []
    for number, text in enumerate(texts, start=1):
        features, inputs = encode_text(encoder, tokenizer, text)
        valid = inputs["attention_mask"][0].astype(bool)
        if not valid.any():
            parser.error(f"text {number} has no valid tokens")
        # The raw encoder is a backbone for fine-tuning. Pool valid rows to illustrate its features.
        pooled = features[0, valid].mean(axis=0)
        norm = float(np.linalg.norm(pooled))
        first_values = ", ".join(f"{value:.6f}" for value in pooled[:6])
        print(f"text {number} per-token features shape: {features.shape}")
        print(f"text {number} mean-pooled first 6: [{first_values}]")
        print(f"text {number} mean-pooled L2 norm: {norm:.6f}")
        pooled_vectors.append(pooled)
        norms.append(norm)

    if len(pooled_vectors) == 2:
        denominator = norms[0] * norms[1]
        if denominator == 0:
            print("cosine similarity: undefined (zero-norm vector)")
        else:
            cosine = float(np.dot(*pooled_vectors)) / denominator
            print(f"cosine similarity: {np.clip(cosine, -1.0, 1.0):.6f}")


if __name__ == "__main__":
    main()