| 446 | const std::optional<core::TensorValue> & condition, |
| 447 | const std::optional<core::TensorValue> & attention_mask, |
| 448 | bool exact_rope) { |
| 449 | auto x = input; |
| 450 | if (weights.output_projection.has_value() && input.shape.last_dim() != weights.dim) { |
| 451 | throw std::runtime_error("MioCodec transformer input projection is not configured for this component"); |
| 452 | } |
| 453 | const auto mask = attention_mask.has_value() |
| 454 | ? *attention_mask |
| 455 | : make_window_mask(constants, weights.heads, input.shape.dims[1], weights.window_size); |
| 456 | std::vector<int32_t> position_values(static_cast<size_t>(input.shape.dims[1]), 0); |
| 457 | for (int64_t i = 0; i < input.shape.dims[1]; ++i) { |
| 458 | position_values[static_cast<size_t>(i)] = static_cast<int32_t>(i); |
| 459 | } |
| 460 | const auto positions = constants.make_tensor( |
| 461 | core::TensorShape::from_dims({input.shape.dims[1]}), |
| 462 | GGML_TYPE_I32, |
| 463 | position_values.data(), |
| 464 | position_values.size() * sizeof(int32_t)); |
| 465 | for (const auto & layer : weights.layers) { |
| 466 | core::TensorValue normed; |
| 467 | std::optional<core::TensorValue> attn_gate; |
| 468 | if (weights.use_adaln) { |
| 469 | if (!condition.has_value() || !layer.attention_adaln.has_value()) { |
| 470 | throw std::runtime_error("MioCodec AdaLN transformer requires condition"); |
| 471 | } |
| 472 | auto out = adaln(ctx, x, *condition, *layer.attention_adaln, weights.dim, true); |
| 473 | normed = out.first; |
| 474 | attn_gate = out.second; |
| 475 | } else { |
| 476 | normed = engine::modules::LayerNormModule({weights.dim, 1.0e-5F, true, true}).build( |
| 477 | ctx, |
| 478 | x, |
| 479 | *layer.attention_norm); |
| 480 | } |
| 481 | auto attn_out = attention(ctx, constants, mask, positions, normed, layer, weights, exact_rope); |
| 482 | if (attn_gate.has_value()) { |
| 483 | attn_out = engine::modules::MulModule{}.build(ctx, attn_out, *attn_gate); |
| 484 | } |
| 485 | x = engine::modules::ResidualAddModule{}.build(ctx, x, attn_out); |
| 486 | |
| 487 | core::TensorValue ffn_normed; |
| 488 | std::optional<core::TensorValue> ffn_gate; |
| 489 | if (weights.use_adaln) { |
| 490 | auto out = adaln(ctx, x, *condition, *layer.feed_forward_adaln, weights.dim, true); |
| 491 | ffn_normed = out.first; |
| 492 | ffn_gate = out.second; |
| 493 | } else { |
| 494 | ffn_normed = engine::modules::LayerNormModule({weights.dim, 1.0e-5F, true, true}).build( |
| 495 | ctx, |
| 496 | x, |
| 497 | *layer.feed_forward_norm); |
| 498 | } |
| 499 | auto ffn_out = swiglu(ctx, ffn_normed, layer, weights.dim, weights.intermediate_dim); |
| 500 | if (ffn_gate.has_value()) { |
| 501 | ffn_out = engine::modules::MulModule{}.build(ctx, ffn_out, *ffn_gate); |
| 502 | } |
| 503 | x = engine::modules::ResidualAddModule{}.build(ctx, x, ffn_out); |
| 504 | } |
| 505 | if (weights.use_adaln) { |
no test coverage detected