guymorganb commited on
Commit
d349c58
·
1 Parent(s): c6d90f3

updated readme with inference example

Browse files
Files changed (1) hide show
  1. README.md +85 -20
README.md CHANGED
@@ -12,26 +12,6 @@ A [Local-Sparse-Global (LSG)](https://arxiv.org/abs/2210.15497) version of [intf
12
 
13
  Below is an example to encode queries and passages from the MS-MARCO passage ranking dataset.
14
 
15
- ```python
16
- from sentence_transformers import SentenceTransformer
17
-
18
- model = SentenceTransformer(
19
- "guymorganb/e5-large-v2-4096-lsg-patched",
20
- {"trust_remote_code": True}
21
- )
22
-
23
- input_texts = [
24
- 'query: how much protein should a female eat',
25
- 'query: summit define',
26
- "passage: As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
27
- "passage: Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments."
28
- ]
29
-
30
- embeddings = model.encode(input_texts, normalize_embeddings=True)
31
- ```
32
-
33
- or...
34
-
35
  ```python
36
  import torch
37
  import torch.nn.functional as F
@@ -92,6 +72,91 @@ embeddings = F.normalize(embeddings, p=2, dim=1)
92
  # 8) Example similarity: compare first two (queries) vs. last two (passages)
93
  scores = (embeddings[:2] @ embeddings[2:].T) * 100
94
  print("Similarity scores:\n", scores.tolist())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  ```
97
  @article{wang2022text,
 
12
 
13
  Below is an example to encode queries and passages from the MS-MARCO passage ranking dataset.
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  ```python
16
  import torch
17
  import torch.nn.functional as F
 
72
  # 8) Example similarity: compare first two (queries) vs. last two (passages)
73
  scores = (embeddings[:2] @ embeddings[2:].T) * 100
74
  print("Similarity scores:\n", scores.tolist())
75
+ ```
76
+
77
+ or...test for inference
78
+
79
+ ```python
80
+ # Modified test script
81
+ import torch
82
+ import torch.nn.functional as F
83
+ from transformers import AutoTokenizer, AutoConfig, AutoModel
84
+ import time
85
+
86
+ # Keep your average_pool function the same
87
+
88
+ model_name = "guymorganb/e5-large-v2-4096-lsg-patched"
89
+
90
+ # Load with explicit LSG settings
91
+ config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
92
+ config.is_decoder = False
93
+ config.block_size = 4096 # Double the block size #############
94
+ config.sparse_block_size = 4096 # Keep equal to block_size ##############
95
+ config.sparsity_factor = 2
96
+ config.sparsity_type = "norm"
97
+ config.adaptive = True
98
+ config.num_global_tokens = 1
99
+ config.pool_with_global = True
100
+
101
+ print("Config after loading:")
102
+ for k, v in config.to_dict().items():
103
+ print(f"{k}: {v}")
104
+
105
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
106
+ model = AutoModel.from_pretrained(
107
+ model_name,
108
+ config=config,
109
+ trust_remote_code=True
110
+ )
111
+ model.eval()
112
+
113
+ # Test with gradually increasing lengths
114
+ test_lengths = [
115
+ 10, # Very short
116
+ 64, #
117
+ 128, #
118
+ 256, #
119
+ 512, #
120
+ 1024, #
121
+ 2048, #
122
+ 3072, #
123
+ 4096 # Full context
124
+ ]
125
+
126
+ for length in test_lengths:
127
+ test_text = f"passage: {'test ' * length }"
128
+
129
+ try:
130
+ encoding = tokenizer(
131
+ test_text,
132
+ max_length=4096,
133
+ padding=True,
134
+ # pad_to_multiple_of=4096, # dont use unless you want a fixed size
135
+ truncation=True,
136
+ return_tensors='pt'
137
+ )
138
+
139
+ actual_length = encoding['input_ids'].size(1)
140
+ print(f"\nTesting length {actual_length} tokens:")
141
+ print(f"Input tensor shape: {encoding['input_ids'].shape}")
142
+
143
+ start = time.time()
144
+ with torch.no_grad():
145
+ encoding["attention_mask"] = encoding["attention_mask"].float()
146
+ outputs = model(**encoding, return_dict=True)
147
+ embeddings = average_pool(outputs.last_hidden_state, encoding["attention_mask"])
148
+ embeddings = F.normalize(embeddings, p=2, dim=1)
149
+
150
+ end = time.time()
151
+ print(f"Success! Processing time: {end - start:.3f} seconds")
152
+ print(f"Embedding shape: {embeddings.shape}")
153
+
154
+ except RuntimeError as e:
155
+ print(f"Failed at length {actual_length}")
156
+ print(f"Error: {str(e)}")
157
+ print(f"Last successful shape: {encoding['input_ids'].shape}")
158
+ break
159
+ ```
160
 
161
  ```
162
  @article{wang2022text,