Views
No views yet
google/embeddinggemma-300m with 10x depth reduction (24 → 2 layers) and 10x embedding width reduction (768 → 76 → 768).google/embeddinggemma-300mpip install torch sentence-transformers transformerssentence-transformers library:1from sentence_transformers import SentenceTransformer
2import torch
3
4# Load the model
5model = SentenceTransformer(
6 "Pieces/embeddinggemma-300m-distilled-depth10pct-10-768dim-best",
7 device="cuda" if torch.cuda.is_available() else "cpu"
8)
9
10# Encode texts
11texts = ["Hello world", "This is a test"]
12embeddings = model.encode(texts, convert_to_tensor=True)
13
14print(f"Embeddings shape: {embeddings.shape}")
15# Output: torch.Size([2, 768])1import torch
2from pathlib import Path
3import sys
4
5# Add parent directory to path for imports
6sys.path.insert(0, str(Path(__file__).parent.parent))
7
8from playground.validate_from_checkpoint import load_trained_model
9from tags_model.training.train_distillation import _get_transformer_layers
10
11# Load the model
12model, config = load_trained_model(
13 checkpoint_path="Pieces/embeddinggemma-300m-distilled-depth10pct-10-768dim-best",
14 device="cuda" if torch.cuda.is_available() else "cpu",
15 compile_model=False,
16)
17
18# Verify structure
19transformer = model.backbone.transformer
20layers = _get_transformer_layers(transformer)
21layer_count = len(layers) if layers else 0
22total_params = sum(p.numel() for p in model.parameters())
23
24print(f"Model structure:")
25print(f" - Layers: {layer_count}")
26print(f" - Parameters: {total_params:,}")
27
28# Encode texts
29model.eval()
30with torch.no_grad():
31 texts = ["Hello world", "This is a test"]
32
33 # Handle Identity projection (when output_dim == embedding_dim)
34 if hasattr(model.backbone, 'projection'):
35 proj = model.backbone.projection
36 is_identity = (
37 isinstance(proj, torch.nn.Identity) or
38 'Identity' in proj.__class__.__name__
39 )
40
41 if is_identity:
42 # Identity projection - encode directly from transformer
43 embeddings = model.backbone.transformer.encode_texts(
44 texts, max_length=512, return_dict=False
45 )
46 else:
47 # Use standard encode_texts which handles projection
48 embeddings = model.backbone.encode_texts(
49 texts, max_length=512, return_dict=False
50 )
51 else:
52 embeddings = model.backbone.encode_texts(
53 texts, max_length=512, return_dict=False
54 )
55
56print(f"Embeddings shape: {embeddings.shape}")1from sentence_transformers import SentenceTransformer
2import torch
3from typing import List
4
5# Load model
6model = SentenceTransformer(
7 "Pieces/embeddinggemma-300m-distilled-depth10pct-10-768dim-best"
8)
9
10def compute_similarities(query_embeddings, tag_embeddings):
11 """Compute cosine similarities between queries and tags."""
12 query_norm = query_embeddings / (query_embeddings.norm(dim=1, keepdim=True) + 1e-8)
13 tag_norm = tag_embeddings / (tag_embeddings.norm(dim=1, keepdim=True) + 1e-8)
14 return torch.mm(query_norm, tag_norm.t())
15
16# Example queries and tags
17queries = [
18 "How to implement authentication in a web application?",
19 "What are the best practices for database optimization?",
20]
21
22tags = [
23 "authentication", "security", "web-development",
24 "database", "sql", "performance", "optimization",
25 "machine-learning", "deployment", "production",
26]
27
28# Encode queries and tags
29query_embeddings = model.encode(queries, convert_to_tensor=True)
30tag_embeddings = model.encode(tags, convert_to_tensor=True)
31
32# Compute similarities
33similarities = compute_similarities(query_embeddings, tag_embeddings)
34
35# Get top tags for each query
36for query_idx, query in enumerate(queries):
37 top_k = 3
38 top_similarities, top_indices = torch.topk(
39 similarities[query_idx], k=top_k, dim=0
40 )
41
42 print(f"\nQuery: {query}")
43 for rank, (tag_idx, sim) in enumerate(
44 zip(top_indices.cpu().tolist(), top_similarities.cpu().tolist()), start=1
45 ):
46 print(f" {rank}. {tags[tag_idx]} (similarity: {sim:.4f})")usage_example.py in this repository for a complete standalone example.1@misc{embeddinggemma-compressed-depth-emb,
2 title={EmbeddingGemma-300M: Depth + Embedding Width Compressed},
3 author={Pieces},
4 year={2024},
5 url={https://huggingface.co/Pieces/embeddinggemma-300m-distilled-depth10pct-10-768dim-best}
6}