| 261 | core::TensorValue reshape_heads( |
| 262 | core::ModuleBuildContext & ctx, |
| 263 | const core::TensorValue & input, |
| 264 | int64_t heads, |
| 265 | int64_t dim) { |
| 266 | return core::reshape_tensor( |
| 267 | ctx, |
| 268 | ensure_contiguous(ctx, input), |
| 269 | core::TensorShape::from_dims({input.shape.dims[0], input.shape.dims[1], heads, dim})); |
| 270 | } |
| 271 | |
| 272 | core::TensorValue attention_from_heads( |
| 273 | core::ModuleBuildContext & ctx, |
| 274 | const core::TensorValue & q_heads, |
| 275 | const core::TensorValue & k_heads, |
| 276 | const core::TensorValue & v_heads, |
| 277 | int64_t dim) { |
| 278 | if (ctx.backend_type == core::BackendType::Cuda) { |
| 279 | return modules::ScaledDotProductAttentionModule({ |
| 280 | dim, |
| 281 | modules::ScaledDotProductAttentionLowering::FlashPreserveViews, |
| 282 | GGML_PREC_F32, |
| 283 | modules::AttentionCausality::NonCausal, |
| 284 | }).build(ctx, q_heads, k_heads, v_heads); |
| 285 | } |
| 286 | |
| 287 | auto scores = matmul_f32( |
| 288 | ctx, |
| 289 | q_heads, |
| 290 | modules::TransposeModule({{0, 1, 3, 2}, k_heads.shape.rank}).build(ctx, k_heads)); |
| 291 | scores = core::wrap_tensor( |
| 292 | ggml_scale(ctx.ggml, ensure_contiguous(ctx, scores).tensor, 1.0f / std::sqrt(static_cast<float>(dim))), |
| 293 | scores.shape, |
| 294 | GGML_TYPE_F32); |
| 295 | scores = ensure_contiguous(ctx, scores); |
| 296 | auto attn = modules::SoftmaxModule{}.build(ctx, scores); |
| 297 | auto context = matmul_f32(ctx, attn, v_heads); |
| 298 | return modules::TransposeModule({{0, 2, 1, 3}, context.shape.rank}).build(ctx, context); |
| 299 | } |
| 300 | |
| 301 | core::TensorValue build_attention( |
| 302 | core::ModuleBuildContext & ctx, |
| 303 | const core::TensorValue & input, |
| 304 | const core::TensorValue & positions, |
| 305 | const AttentionWeights & weights, |
| 306 | const RoformerArchitectureConfig & config) { |
| 307 | const modules::LinearModule q_proj(binding::linear_config(config.dim, config.heads * config.dim_head, false)); |
| 308 | const modules::LinearModule k_proj(binding::linear_config(config.dim, config.heads * config.dim_head, false)); |
| 309 | const modules::LinearModule v_proj(binding::linear_config(config.dim, config.heads * config.dim_head, false)); |
| 310 | const modules::LinearModule gate_proj(binding::linear_config(config.dim, config.heads, true)); |
no test coverage detected