Embedding lookup: select rows from weight matrix by token IDs.
(&self, ids: &Tensor, weight: &Tensor)
| 511 | |
| 512 | /// Embedding lookup: select rows from weight matrix by token IDs. |
| 513 | fn embedding(&self, ids: &Tensor, weight: &Tensor) -> Result<Tensor> { |
| 514 | let hidden_size = weight.dim(1)?; |
| 515 | let dims = ids.dims(); |
| 516 | // Fast path: 1D input — no reshape needed |
| 517 | if dims.len() == 1 { |
| 518 | let selected = weight.index_select(ids, 0)?; |
| 519 | return Ok(selected); |
| 520 | } |
| 521 | // General path: flatten, select, reshape |
| 522 | let elem_count: usize = dims.iter().product(); |
| 523 | let flat_ids = ids.reshape(elem_count)?; |
| 524 | let selected = weight.index_select(&flat_ids, 0)?; |
| 525 | let mut out_shape = dims.to_vec(); |
| 526 | out_shape.push(hidden_size); |
| 527 | selected.reshape(out_shape.as_slice()) |
| 528 | } |
| 529 | |
| 530 | /// Create a causal attention mask. Returns a U8 tensor of shape `(seq_len, kv_len)` |
| 531 | /// where 1 = masked (future position), 0 = attend. |