forked from openvinotoolkit/openvino
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartitioning.cpp
More file actions
2700 lines (2397 loc) · 125 KB
/
partitioning.cpp
File metadata and controls
2700 lines (2397 loc) · 125 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "partitioning.hpp"
#include <memory>
#include "../logging.hpp"
#include "../util.hpp"
#include "intel_npu/config/npuw.hpp"
#include "online/compiler.hpp"
#include "online/utils/utils.hpp" // getMetaDesc
#include "openvino/core/parallel.hpp"
#include "openvino/core/rt_info/weightless_caching_attributes.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/slice.hpp"
#include "openvino/op/util/op_types.hpp"
#include "openvino/pass/validate.hpp"
#include "openvino/runtime/make_tensor.hpp"
#include "openvino/util/common_util.hpp"
#include "openvino/util/xml_parse_utils.hpp"
#include "patterns/dcoff.hpp"
#include "patterns/moe.hpp"
#include "patterns/opt.hpp"
#include "traits.hpp"
namespace ov {
namespace npuw {
inline bool operator==(const std::reference_wrapper<Subgraph>& lhs, const std::reference_wrapper<Subgraph>& rhs) {
ov::npuw::Subgraph& llink = lhs.get();
ov::npuw::Subgraph& rlink = rhs.get();
return &llink == &rlink;
}
} // namespace npuw
} // namespace ov
template <typename T2>
struct std::hash<std::pair<ov::npuw::Subgraph::Ref, T2>> {
std::size_t operator()(const std::pair<ov::npuw::Subgraph::Ref, T2>& p) const noexcept {
ov::npuw::Subgraph& sg = p.first.get();
std::size_t h1 = std::hash<void*>{}(&sg);
std::size_t h2 = std::hash<T2>{}(p.second);
return h1 ^ (h2 << 1);
}
};
namespace std {
template <>
struct hash<ov::Output<ov::Node>> {
inline size_t operator()(const ov::Output<ov::Node>& x) const {
// TODO: use a better hash function
return x.get_node()->get_instance_id() ^ (x.get_index() << 56);
}
};
} // namespace std
namespace {
class FuncallEverywhere {
std::shared_ptr<ov::Model> m_model;
std::set<std::string> m_known;
std::size_t m_new_id = 0u;
mutable bool m_enabled = false;
mutable std::once_flag m_once;
::intel_npu::Config& m_cfg;
public:
explicit FuncallEverywhere(const std::shared_ptr<ov::Model>& model, ::intel_npu::Config& cfg)
: m_model(model),
m_cfg(cfg) {}
void register_known(const std::string fcn_id) {
m_known.insert(fcn_id);
}
std::string register_new() {
std::string new_fcn = "FCEW" + ov::npuw::util::fmt(m_new_id++, 100);
// Just make an assert here: assume we don't need to handle
// collisions
NPUW_ASSERT(m_known.count(new_fcn) == 0);
return new_fcn;
}
bool enabled() const {
std::call_once(m_once, [&]() {
const bool fce_opt = m_cfg.get<::intel_npu::NPUW_FUNCALL_FOR_ALL>();
if (fce_opt) {
LOG_WARN("Every subgraph in " << m_model->get_friendly_name()
<< " will be turned to a function: may cause performance issues");
m_enabled = true;
}
});
return m_enabled;
}
};
struct BankContains {
std::string name;
bool operator()(const ov::npuw::RepeatedBlock::MatchedLayers& lrs) {
return lrs.count(name) > 0;
}
};
struct ProducesResult {
bool operator()(const std::shared_ptr<ov::Node>& node) {
std::set<ov::Input<ov::Node>> all_readers;
for (auto&& out : node->outputs()) {
const auto& these_readers = out.get_target_inputs();
all_readers.insert(these_readers.begin(), these_readers.end());
}
return std::any_of(all_readers.begin(), all_readers.end(), [](const ov::Input<ov::Node>& iport) {
return ov::op::util::is_output(iport.get_node());
});
}
};
ov::npuw::Ensemble load_groups(const std::shared_ptr<ov::Model>& model, const std::string& path_to_plan) {
// Try to load the partitioning plan...
NPUW_ASSERT(!path_to_plan.empty());
std::ifstream ifs(path_to_plan);
if (!ifs) {
LOG_ERROR("Couldn't open " << ::intel_npu::NPUW_PLAN().key() << " pointing to " << path_to_plan << "!");
return {};
}
// If file is specified and it exists, try to parse the XML document
LOG_INFO("Loading plan from " << path_to_plan << "...");
pugi::xml_document xml_doc;
pugi::xml_parse_result xml_res = xml_doc.load_file(path_to_plan.c_str());
if (xml_res.status != pugi::status_ok) {
LOG_ERROR("Couldn't parse the plan XML!");
return {};
}
// Load partitioning structure from the XML document.
// Note the .sg part is not filled at this point
using namespace ov::util::pugixml;
auto root = xml_doc.document_element();
// Load groups first
// clang-format off
std::vector<ov::npuw::Group> partitions;
auto groups = root.child("partitioning");
FOREACH_CHILD(group, groups, "group") {
partitions.push_back(ov::npuw::Group{});
ov::npuw::Group& this_group = partitions.back();
this_group.gflops = get_float_attr(group, "gflops");
this_group.repeated_id = get_str_attr(group, "repeated", "");
this_group.avoid_list = get_str_attr(group, "avoid", "");
this_group.settag(get_str_attr(group, "tag", ""));
FOREACH_CHILD(input, group, "input") {
this_group.input_layers.push_back(get_str_attr(input, "name"));
}
FOREACH_CHILD(output, group, "output") {
this_group.output_layers.push_back(get_str_attr(output, "name"));
}
FOREACH_CHILD(layer, group, "layer") {
this_group.all_layers.push_back(get_str_attr(layer, "name"));
}
}
// Load repeating blocks, if any
std::map<std::string, ov::npuw::RepeatedBlock> repeated;
auto reps = root.child("repeated");
if (reps) {
FOREACH_CHILD(block, reps, "block") {
ov::npuw::RepeatedBlock this_block;
FOREACH_CHILD(match, block, "match") {
ov::npuw::RepeatedBlock::MatchedLayers mls;
FOREACH_CHILD(layer, match, "layer") {
mls.insert(get_str_attr(layer, "name"));
}
this_block.matches.push_back(std::move(mls));
} // match
repeated[get_str_attr(block, "id")] = std::move(this_block);
} // block
} // if(reps)
// clang-format on
LOG_INFO("Found " << repeated.size() << " different repeated block(s)");
return ov::npuw::Ensemble{get_float_attr(root, "gflops"),
get_bool_attr(root, "irregular_io", false),
std::move(partitions),
std::move(repeated)};
}
class Partitioner {
private:
// External state - taken in the consturctor
const std::shared_ptr<ov::Model>& model;
ov::npuw::Ensemble& ens;
ov::npuw::Partitioning& P;
using PPtr = std::shared_ptr<ov::op::v0::Parameter>;
using RPtr = std::shared_ptr<ov::op::v0::Result>;
using SubgParam = std::pair<ov::npuw::Subgraph::Ref, PPtr>;
using SubgResult = std::pair<ov::npuw::Subgraph::Ref, RPtr>;
using LinkPtrTo = std::pair<size_t /*submodel_idx*/
,
PPtr /*param ptr*/
>;
using LinkPtrFrom = std::pair<size_t /*submodel_idx*/
,
RPtr /*result ptr*/
>;
using LinkPtrs = std::map<LinkPtrTo, LinkPtrFrom>;
LinkPtrs subgraph_ptr_links;
// Internal state - not exposed anywhere
struct FunctionPipeline {
using VM = std::vector<std::shared_ptr<ov::Model>>;
using VS = std::vector<ov::npuw::Subgraph::Ref>;
VM mdls;
VS refs;
std::unordered_set<std::shared_ptr<ov::Node>> consts_to_keep;
// Map every function call instance' Parameter and result
// back to its prototype Parameter and Result
std::unordered_map<SubgParam, PPtr> param_call_to_proto;
std::unordered_map<SubgResult, RPtr> result_call_to_proto;
};
std::map<std::string, FunctionPipeline> all_functions;
// NB(dm): Sort of warning here that this mapping is used
// across all functions. Probably it would be easier and
// more efficient to have one per function group
std::unordered_map<std::string, std::string> layer_to_prototype;
// Some of the scalars might be shared by different groups within
// the same repeated block family. We need to keep them counted for sanity checks.
// Matches a pair of {func_name, layer_name} to it's counter.
std::map<std::pair<std::string, std::string>, size_t> dup_scalars;
using Match = std::function<bool(const std::shared_ptr<ov::Node>& node)>;
void propagate(const std::string& func_name, const Match& test, ov::npuw::RepeatedBlock::MatchedBank& bank);
// Helper method to find and cache router model for MoE transformations
// Returns cached router model if available, otherwise searches P.functions
// for a function tagged as "router" and caches it for future use
std::shared_ptr<ov::Model> getRouterModel();
void createFunction(FunctionPipeline& func_ggg);
// NB(dm): This method should get a better place, it is here only because
// it is tied to the Function structure (but, in fact, not so much)
void identifySpatialRange(ov::npuw::Function& f);
template <typename T, typename M>
void rearrange_to_function_protocol(ov::npuw::Subgraph::Ref func_ref,
const std::vector<T>& protocol,
std::vector<T>& call,
const M& call_to_proto,
bool required = false) {
LOG_DEBUG("Rearranging...");
LOG_BLOCK();
LOG_DEBUG("Protocol: " << protocol.size());
for (auto&& p : protocol) {
LOG_BLOCK();
LOG_DEBUG(p);
}
std::vector<T> to_proto;
LOG_DEBUG("Call: " << call.size());
for (auto&& c : call) {
LOG_BLOCK();
auto p_c = call_to_proto.at(typename M::key_type(func_ref, c));
to_proto.push_back(p_c);
LOG_DEBUG(c << " (which is " << p_c << ")");
}
std::vector<T> call_tmp = call;
call = std::vector<T>(protocol.size(), nullptr);
for (std::size_t i = 0; i < protocol.size(); i++) {
auto iter = std::find(to_proto.begin(), to_proto.end(), protocol[i]);
if (iter != to_proto.end()) {
// There was an example in LLama where the last (32th) repeated
// block had 3 outputs instead of 4 with several partitioning models.
std::size_t j = std::distance(to_proto.begin(), iter);
LOG_DEBUG("Put " << j << " element to " << i << " as in the protocol");
call[i] = call_tmp[j];
} else if (required) {
OPENVINO_THROW("NPUW: Parameter from protocol is not found in the call!");
}
}
}
// FIXME: a fix to overcome the model with duplicate friendly names in constants
std::string get_unique_name(const std::shared_ptr<ov::Node> node_ptr) {
if (!node_ptr) {
OPENVINO_THROW("NPUW: Fatal error");
}
if (!ov::is_type<ov::op::v0::Constant>(node_ptr)) {
OPENVINO_THROW("NPUW: trying to get a unique name of a non-Constant node");
}
// FIXME: cache this
return node_ptr->get_friendly_name() + " with meta " + ov::npuw::online::util::getMetaDesc(node_ptr) +
" with output " + (*node_ptr->output(0).get_target_inputs().begin()).get_node()->description();
}
public:
Partitioner(const std::shared_ptr<ov::Model>& _model,
ov::npuw::Ensemble& _ens,
ov::npuw::Partitioning& _P,
::intel_npu::Config& _cfg,
const ov::npuw::PartitioningContext& _ctx)
: model(_model),
ens(_ens),
P(_P),
func_pipeline_type(FunctionPipelineType::FOLD),
cfg(_cfg),
part_ctx(_ctx) {}
////////////////////////////////////////////////////////
// Partitioning execution pipeline
// Partitioning to subgraph mapping
void identifySubgraphs();
// Function folding subroutines
enum class FunctionPipelineType { FOLD, CWAI };
std::vector<std::string> initFunctionPipeline(FunctionPipelineType utype);
// this implicit shared state can be lifted to some new
// kind of object
void propagateSlices(const std::string& func_name);
void propagateConverts(const std::string& func_name);
void propagateWeights(const std::string& func_name);
void propagateScalars(const std::string& func_name);
void propagateConvertsOut(const std::string& func_name);
void sanityCheck(const std::string& func_name);
void saveTinyConstants(const std::string& func_name);
void saveScaleFactors(const std::string& func_name);
void saveRepeatedConstants(const std::string& func_name);
void saveTailDictConstants(const std::string& func_name);
void matchParameters(const std::string& func_name);
void matchResults(const std::string& func_name);
void createFunction(const std::string& func_name);
void matchRepeatedSubgraphs(const std::string& func_name);
void spatial(const std::string& func_name);
void attention(const std::string& func_name);
// MoE-specific transformations (require router model availability)
// transformMoeExperts: Transform expert functions (tag="expert") to optimized MoE expert models
// transformMoeDownstream: Transform downstream processing (pattern-based detection)
void transformMoeExperts(const std::string& func_name);
void transformMoeDownstream(const std::string& func_name);
void optimize(const std::string& func_name);
void decompressionCutOff(const std::string& func_name);
// Final steps
void finalizeLinks();
private:
FunctionPipelineType func_pipeline_type;
::intel_npu::Config& cfg;
ov::npuw::PartitioningContext part_ctx;
std::size_t m_f16ic_counter = 0u;
std::shared_ptr<ov::Node> new_f16ic_cvt(ov::Output<ov::Node> out, ov::element::Type type);
};
std::shared_ptr<ov::Node> Partitioner::new_f16ic_cvt(ov::Output<ov::Node> out, ov::element::Type type) {
// These Converts are added on activations (cross-subgraph connections) when
// the model is being cut. This may end up in Converts added to different
// individual submodels, rather than the one flat original model.
// This, in turn, may cause naming collisions between the newly added Converts
// and, for example, the Converts that was there in the original model.
// Since the substantial part of the FOLDing algorithm still relies on
// operation names (Operation bank matching), this is the point where
// it did break - based on the clashed name match, one Convert was mistakenly
// recognized as some other, resulting in the broken match banks and the failed
// "all_ok" assert.
//
// The below code workarounds the issue by forcing these Convert names be
// unique. Again, there's no guarantee we won't see such Convert names in the
// original model(s), but the probability is quite low here.
auto new_src = std::make_shared<ov::op::v0::Convert>(out, type);
new_src->set_friendly_name("Convert_f16ic_" + std::to_string(m_f16ic_counter++));
return new_src;
}
struct Precalculated_Bound_Const {
static constexpr const char* name = "NPUW::Precalculated_Bound_Const";
};
void Partitioner::identifySubgraphs() {
LOG_INFO("Identifying subgraphs for model " << model->get_friendly_name() << "...");
LOG_BLOCK();
const bool connect_in_f16 = cfg.get<::intel_npu::NPUW_F16IC>() && !ens.irregular_io;
using namespace ov::npuw;
std::vector<ov::npuw::Group>& partitions = ens.groups;
// Apply partitioning changes to the original model
// but first cache all nodes to identify by name
using NodeSPtr = std::shared_ptr<ov::Node>;
std::unordered_map<ov::Output<ov::Node>, LinkPtrFrom> result_cache;
std::unordered_map<std::string, NodeSPtr> node_id_cache;
for (auto&& node_ptr : model->get_ordered_ops()) {
node_id_cache[node_ptr->get_friendly_name()] = node_ptr;
}
LOG_INFO("Caching done: " << node_id_cache.size() << " layers.");
// Accumulate knowledge about known OV layers when walking
// over a topologically-sorted list.
std::unordered_set<NodeSPtr> nodes_known_now;
// FIXME: Need to do some sanity checks here. What if partitioning
// has been generated for another variation of this model?
// What if that was a completely different model?
std::size_t this_group_idx = 0u; // FIXME: Replace with indexed()
for (auto&& group : partitions) {
LOG_INFO("Process partition " << this_group_idx << "...");
LOG_BLOCK();
// Sanity check: all group's layers present in the model
std::unordered_set<NodeSPtr> group_nodes;
for (auto&& layer : group.all_layers) {
auto it = node_id_cache.find(layer);
if (node_id_cache.end() == it) {
OPENVINO_THROW("NPUW: Fatal error - partitition refers to layer \"",
layer,
"\" which was not found in the ov::Model");
}
group_nodes.insert(it->second);
}
group.sg._repeated_id = group.repeated_id;
group.sg._forced_to_fcall = group.forced_to_fcall;
group.sg._gflops = group.gflops;
group.sg._ops = group.all_layers.size();
P.total_ops += group.sg._ops;
group.sg._avoid_list = group.avoid_list;
group.sg.settag(group.gettag());
// Note inputs and outputs are included in the above set, so if
// we are here, those nodes should be present in the model.
// In the subgraph, every "input" layer is the first (top) operation
// in the submodel (meaning it only depends on Parameters and Constants).
// In the original model, though, this layer is connected to smt.
// OpenVINO edge model is following:
// SomeNode:#Output -> #Input:ThisNode.
// In order to properly maintain connectivity of the partitioned model,
// we need to track these connections here.
// FIXME: But for now, just break all the connections!
// Note: input/output layers are _parts of the group_, they are like
// beginning/end of the subgraph.
// Input layers may be connected to the same producer nodes, weights,
// or parameters. Cache those to avoid duplicating the parameters.
std::unordered_map<ov::Output<ov::Node>, NodeSPtr> input_mapping;
// In several cases a model can be slightly altered after the partitioning
// plan was done. E.g., new slices or converts may be added on inputs/
// outputs. Add a special handling for this case.
std::unordered_set<NodeSPtr> extra_params;
auto parameter_as_is = [&input_mapping](const NodeSPtr& orig_node) {
auto it = input_mapping.find(orig_node);
if (it != input_mapping.end()) {
return it->second;
}
input_mapping[orig_node] = orig_node;
return orig_node;
};
auto is_hp_tag = [](auto node) {
auto hptag = node.get_rt_info().find(ov::npuw::util::HighPrecisionAttr::get_type_info_static());
if (hptag == node.get_rt_info().end() ||
hptag->second.template as<ov::npuw::util::HighPrecisionAttr>().compute_precision_type !=
ov::element::f32) {
return false;
}
return true;
};
auto parameter_from = [&input_mapping, is_hp_tag, connect_in_f16](ov::Output<ov::Node> output) {
auto orig_node = output.get_node_shared_ptr();
auto it = input_mapping.find(output);
if (it != input_mapping.end()) {
return it->second;
}
// In some weird combinations we can substitute a run-time parameter
// with a Constant. Normally this happens on ShapeOf/... subgraphs.
// In this case, adding a new parameter in a subnode will only break
// stuff as OpenVINO will be unable to calculate some output tensor
// shapes without tricks. So...
NodeSPtr result;
auto& output_tensor = output.get_tensor();
if (output_tensor.has_and_set_bound()) {
// if has_and_set_bound() == true, lower/upper values are the same tensor.
auto new_const = std::make_shared<ov::op::v0::Constant>(output_tensor.get_upper_value());
new_const->set_friendly_name(ov::npuw::util::Unique<Precalculated_Bound_Const>::name());
result = std::static_pointer_cast<ov::Node>(new_const);
LOG_VERB("Found bound value in " << output << ", substituting it with " << new_const);
} else {
// OK, actually introduce a parameter, cache it, and return.
// Lower the parameter precision here, if required.
// Note: doing so REQUIRES a Convert node to be present here
// to maintain graph contracts. See handling where parameter_from is called.
auto otype = output.get_element_type();
if (otype == ov::element::f32 && connect_in_f16) {
if (!is_hp_tag(output)) {
otype = ov::element::f16;
LOG_DEBUG("Found parameter " << output << ", will be computed in fp16 precision");
} else {
LOG_DEBUG("Found parameter " << output << ", pinned to compute in fp32 precision");
}
}
auto new_param = std::make_shared<ov::op::v0::Parameter>(otype, output.get_partial_shape());
result = std::static_pointer_cast<ov::Node>(new_param);
}
input_mapping[output] = result;
return result;
};
for (auto&& input_layer_name : group.input_layers) {
LOG_VERB("Processing group's input layer " << input_layer_name);
auto input_layer_ptr = node_id_cache.at(input_layer_name);
if (input_layer_ptr->inputs().empty()) {
OPENVINO_THROW("The group's input layer ",
input_layer_name,
" has NO INPUTS!! - Graph contracts are broken??");
}
for (auto&& input_desc : input_layer_ptr->inputs()) {
LOG_BLOCK();
const auto input_node = input_desc.get_source_output().get_node_shared_ptr();
LOG_DEBUG("Checking " << input_node);
if (ov::op::util::is_parameter(input_node)) {
// Input to this subgraph layer is already a Parameter (original graph
// input). Track it among the subgraph parameters and continue.
parameter_as_is(input_node);
} else if (ov::op::util::is_constant(input_node)) {
// Input to this subgraph layer is Const (weight). Don't do anything here.
continue;
} else if (ov::is_type<ov::op::v0::Convert>(input_node) &&
ov::op::util::is_constant(input_node->input(0).get_source_output().get_node_shared_ptr())) {
// "Just-an-op" case, popped here again
// FIXME: Finally introduce my own test routine for that!
// Don't do anything here too.
continue;
} else if ((ov::is_type<ov::op::v8::Slice>(input_node) ||
ov::is_type<ov::op::v0::Convert>(input_node)) &&
!nodes_known_now.count(input_node) &&
ov::op::util::is_parameter(input_node->input(0).get_source_output().get_node_shared_ptr())) {
// So the situation is:
// - a group has an input layer
// - which reads from a Slice or Convert
// - which reads from a Parameter
// - not a part of any prior group
// This happens when an offline plan is used with a kvcache
// model extended with slices to maintain zero-copy (LLM case)
auto extra_param = input_node->input(0).get_source_output().get_node_shared_ptr();
input_mapping[input_node->output(0)] = extra_param;
extra_params.insert(extra_param);
LOG_DEBUG("Registered extra param " << extra_param);
} else {
// Ok, this input is connected to some other node's output
// Replace this connection with a link to a newly created Parameter
// if this connection isn't coming from the same group like in pic below:
//
// [par1] [par2]
// v :
// op1 :
// : .........'
// v v
// op2
// v
// op3
// In this case both op1 and op2 will be marked input layers, but it doesn't
// meen there's nothing _before_ an input layer in the graph
if (group_nodes.find(input_node) == group_nodes.end()) {
// Can't use input_node here directly since parameter_from converts
// ov::Node to Output<Node> which some layers don't support by default.
auto new_param = parameter_from(input_desc.get_source_output());
std::shared_ptr<ov::Node> new_src;
if (new_param->get_element_type() != input_desc.get_element_type()) {
// This is the only case where types may not match
NPUW_ASSERT(input_desc.get_element_type() == ov::element::f32);
NPUW_ASSERT(new_param->get_element_type() == ov::element::f16);
NPUW_ASSERT(connect_in_f16);
new_src = new_f16ic_cvt(new_param, ov::element::f32);
LOG_DEBUG("Added F16IC Param Convert " << new_src << " on top of " << new_param << " for "
<< input_desc);
} else {
new_src = new_param;
}
NPUW_ASSERT(new_src);
ov::copy_runtime_info(input_node, new_src); // NB: Still not sure why do this
input_desc.replace_source_output(new_src);
}
} // if (is..)
} // for (inputs)
} // for (input_layers)
// Transform the accumulated parameters to the subgraph model's input parameter vector
// Also track the connectivity
LOG_VERB("Populating _parameters...");
group.sg._parameters.clear();
// Stabilize input order - sort layers based on names
using PairNodePtr = std::pair<ov::Output<ov::Node>, std::shared_ptr<ov::Node>>;
std::vector<PairNodePtr> input_mapping_sorted(input_mapping.begin(), input_mapping.end());
std::sort(input_mapping_sorted.begin(),
input_mapping_sorted.end(),
[](const PairNodePtr& p1, const PairNodePtr& p2) {
// FIXME: some compilers could potentially compare element with itself
if (p1.first == p2.first) {
return false;
}
// Sanity check
NPUW_ASSERT(p1.first != p2.first);
return p1.first.get_node_shared_ptr()->get_friendly_name() <
p2.first.get_node_shared_ptr()->get_friendly_name();
});
// Now (after unknown slices/converts were introduced) params may be referred to
// from multiple places in the model - so may be added multiple times to the
// input mapping. This is a w/a, better they're added only once (TODO).
// This set handles it.
std::set<std::shared_ptr<ov::Node>> unique_params;
for (auto&& im : input_mapping_sorted) {
LOG_BLOCK();
auto& src_node = im.first;
auto& maybe_param = im.second;
if (ov::op::util::is_parameter(maybe_param) && unique_params.count(maybe_param) == 0) {
// some Parameters could fold into Constants, so only add real parameters
auto this_param = std::static_pointer_cast<ov::op::v0::Parameter>(maybe_param);
group.sg._parameters.push_back(this_param);
unique_params.insert(maybe_param);
if (src_node != this_param && extra_params.count(this_param) == 0) {
// Parameter node and the recorded src node are different
// so it is a cut-off point (see above, parameter_from()):
// - record connectivity between subgraphs.
// Exception: param is registered via slice or convert
const auto& link_from = result_cache.at(src_node);
const auto link_to = LinkPtrTo{this_group_idx, this_param};
subgraph_ptr_links[link_to] = link_from;
}
} else {
// assert is_constant(), there's no other way
}
} // for(input_mapping_sorted)
// The same logic for group's final layers: replace their direct
// connections with Result stubs (but remember where these outputs
// were going to).
LOG_VERB("Populating _results...");
{
// Before populating the output layers, do a quick Result->Output Layer
// propagation to extend out output layers with the layers not mentioned
// in the partitioning plan. This may happen if the plan was already exported,
// but some changes were done to the model (like kvcache regrouping) after
// that.
// The idea is simple: walk over the group's all_layers and check if those
// are producing results. If they are and they're not parts of the output_layers,
// add them there.
// Another case which is handled here is an extra Convert which can be
// set as part of kvcache conversion routune.
LOG_BLOCK();
std::set<std::string> output_layers_cache(group.output_layers.begin(), group.output_layers.end());
// Have to switch clang-format here to make cpplint happy
// clang-format off
for (auto&& op_name : group.all_layers) {
auto layer_ptr = node_id_cache.at(op_name);
if (ProducesResult {}(layer_ptr) && !output_layers_cache.count(op_name)) {
LOG_VERB("Adding " << op_name << " as an extra output layer since it is produces a Result");
output_layers_cache.insert(op_name);
group.output_layers.push_back(op_name);
}
for (auto&& oport : layer_ptr->outputs()) {
for (auto&& inport : oport.get_target_inputs()) {
auto reader_ptr = inport.get_node();
if (ov::is_type<ov::op::v0::Convert>(reader_ptr) &&
ProducesResult {}(reader_ptr->shared_from_this()) &&
!output_layers_cache.count(reader_ptr->get_friendly_name())) {
const auto& cvt_name = reader_ptr->get_friendly_name();
output_layers_cache.insert(cvt_name);
group.output_layers.push_back(cvt_name);
}
}
}
} // for(all_layers)
// clang-format on
}
std::size_t num_optimized_out_layers = 0u;
for (auto&& output_layer_name : group.output_layers) {
LOG_VERB("Processing group's output layer " << output_layer_name);
LOG_BLOCK();
auto output_layer_ptr = node_id_cache.at(output_layer_name);
if (output_layer_ptr->outputs().empty()) {
OPENVINO_THROW("The group's output layer ",
output_layer_name,
" has NO OUTPUTS!! - Graph contracts are broken??");
}
const auto old_results_size = group.sg._results.size();
std::size_t num_optimized_out = 0;
for (auto&& output_desc : output_layer_ptr->outputs()) {
// NOT Every layer's output becomes a Result:
// Some of those can be consumed by the same group, e.g.
//
// op100
// v v v
// : : [res1]
// : v
// : op101
// v
// op102
bool has_external_readers = false;
NodeSPtr maybe_result = nullptr;
auto readers = output_desc.get_target_inputs();
// This is possible then some of layer's outputs are not used in the model.
if (readers.empty()) {
LOG_VERB("Output layer " << output_desc.get_node()->get_friendly_name()
<< " was OPTIMIZED OUT since it has no readers.");
num_optimized_out++;
continue;
}
for (auto&& r : readers) {
// First, remember the connections (to replicate those
// at the npuw::CompiledModel level)
auto reader_node_ptr = r.get_node()->shared_from_this();
if (ov::op::util::is_output(reader_node_ptr)) {
maybe_result = std::move(reader_node_ptr);
} else if (group_nodes.find(reader_node_ptr) == group_nodes.end()) {
has_external_readers = true;
}
}
if (maybe_result) {
// This layer's output was connected to Result already.
// It happens when this layer is the original model's output
// Keep it to make the ugly top-level I/O matching procedure work.
// FIXME: This needs to be refactored
group.sg._results.push_back(ov::as_type_ptr<ov::op::v0::Result>(maybe_result));
result_cache[output_desc] =
LinkPtrFrom{this_group_idx, ov::as_type_ptr<ov::op::v0::Result>(maybe_result)};
} else if (has_external_readers) {
// Introduce and record a new Result
// As the graph is processed in the topological order,
// details recorded about this output at this point will
// be handled as input details for some other subgraph.
if (output_desc.get_tensor().has_and_set_bound()) {
// Note: There is an optimization above where some Parameters
// (down-stream) can be folded to Constants. Same applies to
// Results which are inputs to these parameters. If the value is
// foldable, no need to introduce Result too.
// Actually it is OK for CPU and GPU, but it breaks the NPU plugin.
num_optimized_out++;
LOG_VERB("Discarding " << output_desc << " -- optimized out!");
} else {
// Register a new Result. Optionally, lower it to f16
ov::Output<ov::Node> result_src = output_desc;
if (output_desc.get_element_type() == ov::element::f32 && connect_in_f16) {
if (!is_hp_tag(output_desc)) {
auto new_cvt = new_f16ic_cvt(output_desc, ov::element::f16);
LOG_VERB("Added F16IC Result Convert " << new_cvt << " on top of " << output_desc);
result_src = new_cvt;
} else {
LOG_VERB("Found result " << output_desc << ", pinned to compute in high precision");
}
}
auto new_result = std::make_shared<ov::op::v0::Result>(result_src);
result_cache[output_desc] = LinkPtrFrom{this_group_idx, new_result};
ov::copy_runtime_info(output_desc.get_node_shared_ptr(), new_result);
group.sg._results.push_back(std::move(new_result));
}
}
} // for (outputs)
if (num_optimized_out == output_layer_ptr->outputs().size()) {
num_optimized_out_layers++;
}
const auto new_results_size = group.sg._results.size();
LOG_VERB("Note: Processing the group " << this_group_idx << " output layer " << output_layer_name
<< " added " << new_results_size - old_results_size
<< " new Result node(s)");
} // for (output_layers)
if (group.sg._results.empty()) {
if (num_optimized_out_layers != group.output_layers.size()) {
OPENVINO_THROW("NPUW Fatal: No Results registered for group ", this_group_idx);
} else {
LOG_VERB("Completely optimize out group " << this_group_idx);
group.sg._optimized_out = true;
}
}
this_group_idx++; // FIXME: indexed() is better!
nodes_known_now.insert(group_nodes.begin(), group_nodes.end());
} // for (partitions)
// Return what we've got here
std::vector<Subgraph>& result = P.subgraphs;
result.reserve(partitions.size());
for (auto&& group : partitions) {
result.push_back(std::move(group.sg));
}
}
std::vector<std::string> Partitioner::initFunctionPipeline(FunctionPipelineType utype) {
func_pipeline_type = utype;
// Collect all groups of function call(s) and process them in groups
std::map<std::string, int> idx;
for (auto&& part_sg : P.subgraphs) {
if (!part_sg._repeated_id.empty()) {
auto pfix = "__" + std::to_string(idx[part_sg._repeated_id]++);
const auto& fcid = func_pipeline_type == FunctionPipelineType::FOLD
? part_sg._repeated_id // with folding, functions of the
// same group have the same id
: part_sg._repeated_id + pfix; // with CWAI (which is not checked here)
// every function gets its own id
auto& u = all_functions[fcid];
u.refs.push_back(std::ref(part_sg));
u.mdls.push_back(
std::make_shared<ov::Model>(part_sg._results,
part_sg._sinks,
part_sg._parameters,
model->get_friendly_name() + "_" + part_sg._repeated_id + pfix));
}
}
if (func_pipeline_type == FunctionPipelineType::CWAI) {
// Early return - don't do anything else here.
// Also update repeated_ids to uniques
std::vector<std::string> functions;
for (auto&& p : all_functions) {
functions.push_back(p.first);
p.second.refs.front().get()._repeated_id = p.first;
}
return functions;
}
// Then, populate a list of functions and the early layer_to_prototype mapping.
// The latter will be refined in the following passes.
LOG_VERB("Initialize layer banks...");
std::vector<std::string> functions;
for (auto&& p : all_functions) {
LOG_BLOCK();
functions.push_back(p.first);
LOG_VERB("Processing function group " << p.first);
auto& rep_block = ens.repeated.at(p.first);
LOG_DEBUG("Use " << p.second.mdls.front()->get_friendly_name() << " as a template...");
for (auto&& node_ptr : p.second.mdls.front()->get_ordered_ops()) {
const auto& this_layer_name = node_ptr->get_friendly_name();
auto layer_bank_iter =
std::find_if(rep_block.matches.begin(), rep_block.matches.end(), BankContains{this_layer_name});
if (layer_bank_iter != rep_block.matches.end()) {
for (auto&& layer : *layer_bank_iter) {
LOG_BLOCK();
LOG_DEBUG(this_layer_name << " is a prototype of " << layer);
layer_to_prototype[layer] = this_layer_name; // Link to self is ok
}
}
}
}
LOG_VERB("Done");
return functions;
}
void Partitioner::propagate(const std::string& func_name,
const Match& test,
ov::npuw::RepeatedBlock::MatchedBank& bank) {
// NOTE: This routine assumes a Const is accessed by a single reader.
// There may be situations where a Const (normally, not a Weight)
// is accessed by multiple readers. This routine shouldn't be used
// there.
auto& model_group = all_functions.at(func_name).mdls;
// PROTO writer (value) <OF> PROTO reader/port (key).
// Readers are always registered in the bank (NOTE: _some_
// bank, but probably not exactly the one which is passed
// here as `bank' argument),
// and Writers are subjects to this propagation process
// (e.g. Convert! -> Op, Const! -> Convert)
using ProtoReader = std::pair<std::string, size_t>;
using ProtoReaders = std::set<ProtoReader>;
auto dump_readers = [](const ProtoReaders& readers) {
LOG_BLOCK();
for (auto&& r : readers)
LOG_DEBUG(r.first << " : " << r.second);
};
std::map<ProtoReaders, std::string> proto_writer_of;
for (auto&& model : model_group) {
LOG_DEBUG("Process function call " << model->get_friendly_name() << "...");
LOG_BLOCK();
// Cache model contents as sometimes Readers of Consts
// may be outside. FIXME: Do only once when a tmp Model is created?
std::unordered_set<ov::Node*> this_model_nodes;
for (auto&& node_ptr : model->get_ordered_ops()) {
this_model_nodes.insert(node_ptr.get());
}
for (auto&& node_ptr : model->get_ordered_ops()) {
if (test(node_ptr)) {
LOG_DEBUG("Process node " << node_ptr);
const auto& this_layer_name = ov::is_type<ov::op::v0::Constant>(node_ptr)
? get_unique_name(node_ptr)
: node_ptr->get_friendly_name();
ProtoReaders this_node_readers, this_node_proto_readers;
for (auto&& this_reader_iport : node_ptr->output(0).get_target_inputs()) {
LOG_BLOCK();
LOG_DEBUG("Read by " << this_reader_iport);
if (this_model_nodes.count(this_reader_iport.get_node()) == 0) {
LOG_BLOCK();
LOG_DEBUG("Link to the external reader (other submodel?) - skip");
} else {
this_node_readers.insert(ProtoReader{this_reader_iport.get_node()->get_friendly_name(),
this_reader_iport.get_index()});
}
} // for(this_reader_iport)
LOG_DEBUG("Looking for proto accessess...");
for (auto&& this_node_reader : this_node_readers) {
LOG_BLOCK();
LOG_DEBUG("Looking for proto of reader " << this_node_reader.first);
this_node_proto_readers.insert(
{layer_to_prototype.at(this_node_reader.first), this_node_reader.second});
}
auto bank_writer_iter = proto_writer_of.find(this_node_proto_readers);
if (bank_writer_iter == proto_writer_of.end()) {
// FIXME: assert(bank_reader_name == proto(bank_reader_name))
// This is a first occasion for this Writer -> Reader pair.
// Register it for the further reference. Also add it to the layer bank
LOG_DEBUG("Register that " << this_layer_name << " is accessed by:");
dump_readers(this_node_proto_readers);
proto_writer_of[this_node_proto_readers] = this_layer_name;
layer_to_prototype[this_layer_name] = this_layer_name;
bank.push_back({this_layer_name});
} else {
// Such occasion is already registered - find a suitable bank
// and add node there
const auto& this_writer_proto = bank_writer_iter->second;
auto suitable_bank_iter = std::find_if(bank.begin(), bank.end(), BankContains{this_writer_proto});
if (suitable_bank_iter == bank.end()) {
OPENVINO_THROW("Fatal: no suitable bank found");
}
// FIXME: add IF(DEBUG) to put the whole thing under condition
LOG_DEBUG("Register that " << this_layer_name << " is in fact " << this_writer_proto);
LOG_DEBUG("- As it is read by:");
dump_readers(this_node_readers);
LOG_DEBUG("- Which in turn are:");
dump_readers(this_node_proto_readers);
suitable_bank_iter->insert(this_layer_name);
layer_to_prototype[this_layer_name] = this_writer_proto;
} // if(iter==end)
} // test(node_ptr)
} // for(ordered_ops)
} // for(each)
} // propagate
void Partitioner::propagateSlices(const std::string& func_name) {
LOG_VERB("Propagate Slice nodes to matching banks for model " << model->get_friendly_name() << "...");
LOG_BLOCK();
// This is a special step. Normally we shouldn't do this here at all.
// Extra slices may be added to the LLM kvcache models _after_
// offline partitioning was done when adapting them to the zero
// -copy kvcache path. In this case, we get extra slices in the model
// which we need to add to the match banks
auto& bank = ens.repeated.at(func_name).matches;
auto match_fcn = [&](const std::shared_ptr<ov::Node>& node_ptr) -> bool {
const auto& this_layer_name = node_ptr->get_friendly_name();
return ov::is_type<ov::op::v8::Slice>(node_ptr) &&
bank.end() == std::find_if(bank.begin(), bank.end(), BankContains{this_layer_name}) // (0)
&& ov::op::util::is_parameter(node_ptr->input(0).get_source_output().get_node_shared_ptr()) // (1)
&& [&](std::set<ov::Input<ov::Node>>&& readers) -> bool {
// FIXME: It could be all_of, but slices may have reads
// outside of the function group (e.g., a single instance
// of shape_of, taken only on the first kvcache tensor)
return std::any_of(readers.begin(), readers.end(), [&](const ov::Input<ov::Node>& reader) -> bool {
auto reply =
bank.end() !=
std::find_if(bank.begin(), bank.end(), BankContains{reader.get_node()->get_friendly_name()});
return reply;
});
}(node_ptr->output(0).get_target_inputs());
};
propagate(func_name, match_fcn, bank);
LOG_VERB("Done");
}
void Partitioner::propagateConverts(const std::string& func_name) {
LOG_VERB("Propagate Convert nodes to matching banks for model " << model->get_friendly_name() << "...");
LOG_BLOCK();
// This is a special step. Normally we shouldn't do this here at all.
// Here comes the original problem description:
//