leochen085 commited on
Commit
928140f
·
verified ·
1 Parent(s): 23a0f7f

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +284 -5
README.md CHANGED
@@ -1,10 +1,289 @@
1
  ---
2
- license: mit
3
- datasets:
4
- - LeoChen085/SlipDataset
5
- - LeoChen085/SlipSFTDataset
6
  language:
7
  - en
 
 
 
 
 
 
 
 
8
  base_model:
9
  - google/gemma-3-270m
10
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
 
 
 
 
2
  language:
3
  - en
4
+ license: mit
5
+ tags:
6
+ - slip
7
+ - time-series
8
+ - sensor
9
+ - multimodal
10
+ - contrastive-learning
11
+ - custom_code
12
  base_model:
13
  - google/gemma-3-270m
14
+ datasets:
15
+ - LeoChen085/SlipDataset
16
+ - LeoChen085/SlipSFTDataset
17
+ pipeline_tag: feature-extraction
18
+ ---
19
+
20
+ # SLIP: Sensor Language-Informed Pretraining
21
+
22
+ **Learning Transferable Sensor Models via Language-Informed Pretraining**
23
+
24
+ Yuliang Chen, Arvind Pillai, Yu Yvonne Wu, Tess Z. Griffin, Lisa Marsch, Michael V. Heinz, Nicholas C. Jacobson, Andrew Campbell
25
+
26
+ *Dartmouth College*
27
+
28
+ [[Paper]](asset/manuscript.pdf) [[Code]](https://github.com/LeoChen085/SLIP) [[Dataset]](https://huggingface.co/datasets/LeoChen085/SlipDataset) [[SFT Dataset]](https://huggingface.co/datasets/LeoChen085/SlipSFTDataset)
29
+
30
+ ---
31
+
32
+ ## Overview
33
+
34
+ SLIP is a multimodal pretraining framework that learns language-aligned sensor representations transferable across diverse sensor setups. It integrates CLIP-style contrastive alignment with sensor-conditioned captioning, enabling both discriminative understanding and generative reasoning over multivariate time series from heterogeneous sensors.
35
+
36
+ **Key features:**
37
+ - **FlexMLP**: A weight-sharing patch embedding that dynamically adapts to different temporal resolutions and variable-length inputs without retraining
38
+ - **Repurposed decoder-only LLM**: Splits a pretrained Gemma-3-270M into a unimodal text encoder (first 12 layers) and a multimodal decoder (last 6 layers with cross-attention), enabling efficient sensor-conditioned text generation
39
+ - **Contrastive + Captioning pretraining**: Joint CLIP-style contrastive loss and autoregressive captioning loss for both discriminative and generative capabilities
40
+ - **Cross-domain transfer**: Pretrained on 600K+ sensor-caption pairs (~1B time points) spanning health, environment, IoT, energy, and transportation
41
+
42
+ ## Architecture
43
+
44
+ SLIP comprises four components:
45
+
46
+ 1. **Sensor Encoder** (120M params): Transformer with FlexMLP patch embedding and 2D RoPE for cross-sensor and long-range temporal interactions
47
+ 2. **Sensor Pooler**: Attention pooling with 65 learnable queries (1 CLS + 64 caption tokens) compressing variable-length sensor tokens to fixed-size representations
48
+ 3. **Text Encoder**: First 12 layers of Gemma-3-270M (last 4 layers unfrozen during pretraining)
49
+ 4. **Multimodal Decoder**: Last 6 layers of Gemma-3-270M extended with cross-attention for sensor-conditioned generation
50
+
51
+ **Total: ~220M parameters, 67M trainable.**
52
+
53
+ ## Results
54
+
55
+ | Task | Metric | Score |
56
+ |------|--------|-------|
57
+ | Linear Probing (11 datasets avg.) | Accuracy | 77.14% |
58
+ | Sensor-based QA | Accuracy | 64.83% |
59
+ | Sensor Captioning | BERTScore | 0.887 |
60
+
61
+ Linear probing accuracy represents a **5.93% relative improvement** over baselines across 11 diverse datasets.
62
+
63
+ ## Checkpoints
64
+
65
+ | File | Description |
66
+ |------|-------------|
67
+ | `model.safetensors` | Pretrained SLIP base model |
68
+ | `har.safetensors` | SFT for HAR chain-of-thought QA |
69
+ | `sleep.safetensors` | SFT for Sleep stage chain-of-thought QA |
70
+ | `ecg.safetensors` | SFT for ECG-QA chain-of-thought QA |
71
+ | `tsqa.safetensors` | SFT for time series QA |
72
+ | `caption.safetensors` | SFT for M4 sensor captioning |
73
+
74
+ ## Installation
75
+
76
+ ```bash
77
+ conda create -n slip python=3.10 -y && conda activate slip
78
+ pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121
79
+ pip install -r requirement.txt
80
+ ```
81
+
82
+ Download checkpoints:
83
+
84
+ ```python
85
+ from huggingface_hub import hf_hub_download
86
+
87
+ hf_hub_download("LeoChen085/SLIP", "SLIP_gemma270.pth", local_dir="ckpt")
88
+
89
+ # Optional: task-specific SFT checkpoints
90
+ for name in ["har", "sleep", "ecg", "tsqa", "caption"]:
91
+ hf_hub_download("LeoChen085/SLIP", f"{name}.safetensors", local_dir="ckpt")
92
+ ```
93
+
94
+ ## Quick Start
95
+
96
+ ### Load Model
97
+
98
+ ```python
99
+ from transformers import AutoModel, AutoTokenizer
100
+
101
+ model = AutoModel.from_pretrained("LeoChen085/SLIP", trust_remote_code=True)
102
+ tokenizer = AutoTokenizer.from_pretrained("google/gemma-3-270m")
103
+ model.eval()
104
+ ```
105
+
106
+ ### Get Contrastive Embeddings
107
+
108
+ ```python
109
+ import torch
110
+
111
+ device = "cuda" if torch.cuda.is_available() else "cpu"
112
+ model = model.to(device)
113
+
114
+ # Build sensor input (flexi-patch format)
115
+ batch_size, num_vars, num_patches, patch_size = 2, 3, 10, 16
116
+ sensor_ids, sensor_masks, sensor_times = [], [], []
117
+ for _ in range(batch_size):
118
+ vars_x, vars_m, vars_t = [], [], []
119
+ for _ in range(num_vars):
120
+ vars_x.append(torch.randn(num_patches, patch_size, device=device))
121
+ vars_m.append(torch.ones(num_patches, patch_size, device=device))
122
+ vars_t.append(
123
+ torch.linspace(0, 1, num_patches, device=device)
124
+ .unsqueeze(-1).expand(num_patches, patch_size)
125
+ )
126
+ sensor_ids.append(vars_x)
127
+ sensor_masks.append(vars_m)
128
+ sensor_times.append(vars_t)
129
+
130
+ sensors = {
131
+ "input_ids": sensor_ids,
132
+ "attention_mask": sensor_masks,
133
+ "time_index": sensor_times,
134
+ }
135
+
136
+ queries = ["Describe the pattern of this sensor data.", "What activity is this?"]
137
+ tok = tokenizer(queries, return_tensors="pt", padding=True, truncation=True, max_length=64)
138
+ text = {k: v.to(device) for k, v in tok.items()}
139
+
140
+ with torch.no_grad():
141
+ text_emb, sensor_emb = model.get_embedding(text, sensors)
142
+
143
+ # text_emb / sensor_emb shape: (batch_size, 640)
144
+ sim = torch.nn.functional.cosine_similarity(text_emb, sensor_emb)
145
+ print(f"Cosine similarity: {sim.tolist()}")
146
+ ```
147
+
148
+ ### Generate Text Conditioned on Sensor Data
149
+
150
+ ```python
151
+ prompt = "This sensor reading indicates"
152
+ gen_tok = tokenizer([prompt] * batch_size, return_tensors="pt", padding=True)
153
+ gen_text = {k: v.to(device) for k, v in gen_tok.items()}
154
+
155
+ with torch.no_grad():
156
+ output_ids = model.generate(gen_text, sensors, max_new_tokens=50)
157
+
158
+ for i, ids in enumerate(output_ids):
159
+ print(f"Sample {i}: {tokenizer.decode(ids, skip_special_tokens=True)}")
160
+ ```
161
+
162
+ ### Get Sensor-Only Embeddings (No Text Needed)
163
+
164
+ ```python
165
+ with torch.no_grad():
166
+ sensor_emb = model.get_sensor_embedding(
167
+ input_ids=sensors["input_ids"],
168
+ mask=sensors["attention_mask"],
169
+ time_index=sensors["time_index"],
170
+ )
171
+ # sensor_emb shape: (batch_size, 640)
172
+ ```
173
+
174
+ ### Load Task-Specific SFT Checkpoint
175
+
176
+ ```python
177
+ from huggingface_hub import hf_hub_download
178
+ from safetensors.torch import load_file
179
+
180
+ har_path = hf_hub_download("LeoChen085/SLIP", "har.safetensors")
181
+ result = model.load_state_dict(load_file(har_path, device=str(device)), strict=False)
182
+ print(f"Loaded HAR checkpoint — missing: {len(result.missing_keys)}, unexpected: {len(result.unexpected_keys)}")
183
+ ```
184
+
185
+ ### SFT Inference: Question Answering over Sensor Data
186
+
187
+ The SFT checkpoints enable natural-language Q&A directly on sensor signals. Each sample pairs a multivariate time series with a formatted prompt; the model generates a chain-of-thought reasoning trace followed by the final answer.
188
+
189
+ **Input format** (from the SFT dataset):
190
+ ```
191
+ [sensor description / context]
192
+ Question: <question about the sensor data>
193
+ Answer:
194
+ ```
195
+ The model continues from `Answer:` and produces the full response.
196
+
197
+ **End-to-end inference example** (using `har_cot` as an example task):
198
+
199
+ ```python
200
+ import torch
201
+ from transformers import AutoModel, AutoTokenizer
202
+ from huggingface_hub import hf_hub_download
203
+ from safetensors.torch import load_file
204
+ from torch.utils.data import DataLoader
205
+ from util.dataset import SftDataset, SFTCollator
206
+
207
+ device = "cuda" if torch.cuda.is_available() else "cpu"
208
+
209
+ # 1. Load base model and tokenizer
210
+ model = AutoModel.from_pretrained("LeoChen085/SLIP", trust_remote_code=True)
211
+ tokenizer = AutoTokenizer.from_pretrained("google/gemma-3-270m")
212
+ model.eval().to(device)
213
+
214
+ # 2. Swap in the HAR SFT checkpoint
215
+ har_path = hf_hub_download("LeoChen085/SLIP", "har.safetensors")
216
+ model.load_state_dict(load_file(har_path, device=str(device)), strict=False)
217
+
218
+ # 3. Load SFT test data (auto-downloaded from HuggingFace)
219
+ test_set = SftDataset("har_cot", split="test", hf_repo="LeoChen085/SlipSFTDataset")
220
+ # is_test=True feeds only the prompt; answer is held out for evaluation
221
+ loader = DataLoader(test_set, batch_size=8,
222
+ collate_fn=SFTCollator(tokenizer, max_len=2880, is_test=True))
223
+
224
+ batch = next(iter(loader))
225
+ sensor = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in batch["sensor"].items()}
226
+ text = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in batch["text"].items()}
227
+
228
+ # 4. Generate the answer
229
+ with torch.no_grad():
230
+ output_ids = model.generate(text, sensor, max_new_tokens=200)
231
+
232
+ # Strip the prompt from the output — keep only the newly generated tokens
233
+ prompts = tokenizer.batch_decode(text["input_ids"], skip_special_tokens=True)
234
+ answers = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
235
+ ground_truths = text["labels"] # list of strings when is_test=True
236
+
237
+ idx = 3
238
+ answer_only = answers[idx][len(prompts[idx]):].strip()
239
+
240
+ print("=== Model answer ===")
241
+ print(answer_only)
242
+ # The accelerometer data over the 2.56 second window shows relatively low
243
+ # variability and consistent patterns across the X, Y, and Z axes. The lack of
244
+ # large, rapid changes in acceleration across all axes suggests minimal physical
245
+ # activity, consistent with a stationary position. Answer: sitting.
246
+
247
+ print("\n=== Ground truth ===")
248
+ print(ground_truths[idx])
249
+ # The sustained low variability following the initial adjustment is characteristic
250
+ # of a sedentary behavior. Answer: sitting.
251
+ ```
252
+
253
+ **Available SFT tasks and their checkpoints:**
254
+
255
+ | Task | Checkpoint | Description |
256
+ |------|-----------|-------------|
257
+ | `har_cot` | `har.safetensors` | Human activity recognition with chain-of-thought (walking, running, cycling, …) |
258
+ | `sleep_cot` | `sleep.safetensors` | Sleep stage classification with CoT (Wake, N1, N2, N3, REM) |
259
+ | `ecg_cot` | `ecg.safetensors` | ECG morphology QA with CoT (normal/abnormal, rhythm, intervals) |
260
+ | `tsqa` | `tsqa.safetensors` | General time-series multiple-choice QA |
261
+ | `m4_caption` | `caption.safetensors` | Free-form natural-language captioning of M4 sensor traces |
262
+
263
+ Replace `"har_cot"` / `"har.safetensors"` with any row from the table above to switch tasks.
264
+
265
+ ## Evaluation Datasets
266
+
267
+ The 11 evaluation datasets span four domains:
268
+
269
+ | Domain | Datasets |
270
+ |--------|----------|
271
+ | Activity Recognition | WISDM, UCI-HAR |
272
+ | Clinical Diagnosis | Stroke (PPG_CVA), Diabetes (PPG_DM), Hypertension (PPG_HTN), Sleep Stage (sleepEDF), Heart Condition (ptbxl) |
273
+ | Stress Prediction | WESAD, StudentLife |
274
+ | Urban Sensing | AsphaltObstacles, Beijing AQI |
275
+
276
+ ## Citation
277
+
278
+ ```bibtex
279
+ @article{chen2026slip,
280
+ title={Learning Transferable Sensor Models via Language-Informed Pretraining},
281
+ author={Chen, Yuliang and Pillai, Arvind and Wu, Yu Yvonne and Griffin, Tess Z. and Marsch, Lisa and Heinz, Michael V. and Jacobson, Nicholas C. and Campbell, Andrew},
282
+ journal={Preprint},
283
+ year={2026}
284
+ }
285
+ ```
286
+
287
+ ## License
288
+
289
+ This project is licensed under the [MIT License](LICENSE).