Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include "core/session/environment.h"
 
#include <algorithm>
#include <array>
#include <gsl/gsl>
 
#include "core/common/basic_types.h"
#include "core/common/safeint.h"
#include "core/framework/allocator.h"
#include "core/framework/allocator_utils.h"
#include "core/framework/error_code_helper.h"
#include "core/framework/plugin_data_transfer.h"
#include "core/graph/constants.h"
#include "core/graph/op.h"
#include "core/platform/device_discovery.h"
#include "core/session/abi_session_options_impl.h"
#include "core/session/allocator_adapters.h"
#include "core/session/inference_session.h"
#include "core/session/onnxruntime_env_config_keys.h"
#include "core/session/onnxruntime_ep_device_ep_metadata_keys.h"
#include "core/session/plugin_ep/ep_allocator_utils.h"
#include "core/session/plugin_ep/ep_factory_internal.h"
#include "core/session/plugin_ep/ep_library_internal.h"
#include "core/session/plugin_ep/ep_library_plugin.h"
#include "core/session/plugin_ep/ep_library_provider_bridge.h"
#include "core/session/plugin_ep/ep_static_plugins.h"
#include "core/session/ort_apis.h"
#include "core/session/utils.h"
 
#if !defined(ORT_MINIMAL_BUILD)
#include "onnx/defs/operator_sets.h"
#include "onnx/defs/operator_sets_ml.h"
#include "core/graph/contrib_ops/internal_nhwc_onnx_schemas.h"
#include "core/graph/contrib_ops/ms_opset.h"
#include "core/graph/contrib_ops/onnx_deprecated_opset.h"
#if defined(ENABLE_TRAINING_OPS)
#include "onnx/defs/operator_sets_training.h"
#endif
#endif
#ifndef DISABLE_CONTRIB_OPS
#include "core/graph/contrib_ops/contrib_defs.h"
#endif
#ifdef USE_DML
#include "core/graph/dml_ops/dml_defs.h"
#endif
 
#include "core/platform/env.h"
#include "core/util/thread_utils.h"
 
#ifdef ONNXRUNTIME_ENABLE_INSTRUMENT
#include "core/platform/tracing.h"
#endif
 
#if defined(ENABLE_TRAINING_OPS)
#include "orttraining/core/graph/training_op_defs.h"
#endif
#ifdef ENABLE_TRAINING
#include "orttraining/core/graph/gradient_builder_registry.h"
#include "orttraining/core/graph/optimizer_builder.h"
#include "orttraining/core/graph/optimizer_graph_builder_registry.h"
#include "orttraining/core/graph/loss_function_registry.h"
#include "orttraining/core/optimizer/graph_transformer_registry.h"
#endif
 
#if !defined(NDEBUG) && defined(__linux__) && !defined(__ANDROID__)
#include "absl/debugging/symbolize.h"
#endif
 
#if defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE)
#include "core/providers/cuda/cuda_provider_factory.h"
#include "core/providers/cuda/cuda_execution_provider_info.h"
#endif
namespace onnxruntime {
using namespace ::onnxruntime::common;
using namespace ONNX_NAMESPACE;
 
std::once_flag schemaRegistrationOnceFlag;
std::once_flag symbolizerInitOnceFlag;
#if defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE)
ProviderInfo_CUDA& GetProviderInfo_CUDA();
#endif  // defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE)
 
namespace {
// Ignore whether there is an arena wrapping the allocator by excluding OrtMemoryInfo.alloc_type from the comparison.
static bool AreOrtMemoryInfosEquivalent(
    const OrtMemoryInfo& left, const OrtMemoryInfo& right,
    bool match_name = true,
    bool ignore_alignment = false) {
  return left.mem_type == right.mem_type &&
         (ignore_alignment ? left.device.EqualIgnoringAlignment(right.device) : left.device == right.device) &&
         (!match_name || left.name == right.name);
}
 
std::vector<AllocatorPtr>::const_iterator FindExistingAllocator(const std::vector<AllocatorPtr>& allocators,
                                                                const OrtMemoryInfo& mem_info,
                                                                bool match_name = true,
                                                                bool ignore_alignment = false) {
  auto ite = std::find_if(std::begin(allocators),
                          std::end(allocators),
                          [&mem_info, match_name, ignore_alignment](const AllocatorPtr& alloc_ptr) {
                            // We want to do the equality checking of 2 OrtMemoryInfos sans the OrtAllocatorType field.
                            // This is because we want to avoid registering two allocators for the same device that just
                            // differ on OrtAllocatorType.
                            // To be more specific, we want to avoid the scenario where the user calls CreateAndRegiserAllocator()
                            // and registers the ORT-internal arena allocator and then tries to register their own custom
                            // allocator using RegisterAllocator() for the same device that has an OrtAllocatorType as
                            // OrtDeviceAllocator (which is the only accepted value while registering a custom allocator).
                            // If we allowed this, it could potentially cause a lot of confusion as to which shared allocator
                            // to use for that device and we want to avoid having any ugly logic around this.
                            return AreOrtMemoryInfosEquivalent(alloc_ptr->Info(), mem_info,
                                                               match_name, ignore_alignment);
                          });
 
  return ite;
}
 
std::unordered_set<OrtAllocator*>::const_iterator FindExistingAllocator(const std::unordered_set<OrtAllocator*>& allocators,
                                                                        const OrtMemoryInfo& mem_info,
                                                                        bool match_name = true) {
  return std::find_if(std::begin(allocators),
                      std::end(allocators),
                      [&mem_info, match_name](const OrtAllocator* alloc_ptr) {
                        const auto* alloc_mem_info = alloc_ptr->Info(alloc_ptr);
                        return AreOrtMemoryInfosEquivalent(*alloc_mem_info, mem_info, match_name);
                      });
}
}  // namespace
 
Status Environment::Create(std::unique_ptr<logging::LoggingManager> logging_manager,
                           std::unique_ptr<Environment>& environment,
                           const OrtThreadingOptions* tp_options,
                           bool create_global_thread_pools,
                           const OrtKeyValuePairs* config_entries) {
  environment = std::make_unique<Environment>();
  auto status = environment->Initialize(std::move(logging_manager), tp_options, create_global_thread_pools,
                                        config_entries);
  return status;
}
 
Status Environment::RegisterAllocator(OrtAllocator* allocator) {
  std::lock_guard<std::mutex> lock{mutex_};
 
  auto allocator_ptr = std::make_shared<IAllocatorImplWrappingOrtAllocator>(allocator);
 
  // for the public API we always want to replace any existing allocator for the device.
  auto status = RegisterAllocatorImpl(allocator_ptr);
 
  // update shared_ort_allocators_
  if (status.IsOK()) {
    if (auto it = FindExistingAllocator(shared_ort_allocators_, *allocator->Info(allocator), /*match_name*/ true);
        it != shared_ort_allocators_.end()) {
      shared_ort_allocators_.erase(it);
    }
 
    shared_ort_allocators_.insert(allocator);
  }
 
  return status;
}
 
Status Environment::RegisterAllocatorImpl(AllocatorPtr allocator) {
  const auto& mem_info = allocator->Info();
 
  const bool match_name = false;
  if (FindExistingAllocator(shared_allocators_, mem_info, match_name) != shared_allocators_.end()) {
    ORT_RETURN_IF_ERROR(UnregisterAllocatorImpl(mem_info, match_name));
  }
 
  shared_allocators_.push_back(std::move(allocator));
 
  return Status::OK();
}
Status Environment::UnregisterAllocator(const OrtMemoryInfo& mem_info) {
  std::lock_guard<std::mutex> lock{mutex_};
 
  return UnregisterAllocatorImpl(mem_info);
}
 
Status Environment::UnregisterAllocatorImpl(const OrtMemoryInfo& mem_info, bool error_if_not_found) {
  auto it = FindExistingAllocator(shared_allocators_, mem_info);
  const bool found_shared_allocator = it != shared_allocators_.end();
  if (!found_shared_allocator && error_if_not_found) {
    return Status(ONNXRUNTIME, INVALID_ARGUMENT, "No allocator for this device has been registered for sharing.");
  }
 
  // we need to remove from shared_ort_allocators_ first in case the entry in shared_allocators_ owns the pointer in
  // shared_ort_allocators_
  // e.g. a plug-in EP allocator is an IAllocatorImplWrappingOrtAllocator that owns the OrtAllocator* created by the EP
  // so when we remove that from shared_allocators_ we release the OrtAllocator instance.
 
  // shared_ort_allocators_ are internal only so never an error if there's no match
  if (auto it2 = FindExistingAllocator(shared_ort_allocators_, mem_info); it2 != shared_ort_allocators_.end()) {
    shared_ort_allocators_.erase(it2);
  }
 
  if (found_shared_allocator) {
    shared_allocators_.erase(it);
  }
 
  return Status::OK();
}
 
Status Environment::CreateAndRegisterAllocator(const OrtMemoryInfo& mem_info, const OrtArenaCfg* arena_cfg) {
  // TODO should we allow sharing of non-CPU allocators?
  if (mem_info.device.Type() != OrtDevice::CPU) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "Only CPU devices are supported. Please call CreateAndRegisterAllocatorV2() for other device.");
  }
 
  // determine if arena should be used
  const bool create_arena = DoesCpuAllocatorSupportArenaUsage()
                                ? (mem_info.alloc_type == OrtArenaAllocator)
                                : false;
 
  AllocatorPtr allocator_ptr;
  // create appropriate DeviceAllocatorRegistrationInfo and allocator based on create_arena
  if (create_arena) {
    // defaults in case arena_cfg is nullptr (not supplied by the user)
    size_t max_mem = 0;
    int arena_extend_strategy = -1;
    int initial_chunk_size_bytes = -1;
    int max_dead_bytes_per_chunk = -1;
    int initial_growth_chunk_size_bytes = -1;
    int64_t max_power_of_two_extend_bytes = -1L;
 
    // override with values from the user supplied arena_cfg object
    if (arena_cfg) {
      max_mem = arena_cfg->max_mem;
      arena_extend_strategy = arena_cfg->arena_extend_strategy;
      initial_chunk_size_bytes = arena_cfg->initial_chunk_size_bytes;
      max_dead_bytes_per_chunk = arena_cfg->max_dead_bytes_per_chunk;
      initial_growth_chunk_size_bytes = arena_cfg->initial_growth_chunk_size_bytes;
      max_power_of_two_extend_bytes = arena_cfg->max_power_of_two_extend_bytes;
    }
 
    OrtArenaCfg l_arena_cfg{max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk,
                            initial_growth_chunk_size_bytes, max_power_of_two_extend_bytes};
    AllocatorCreationInfo alloc_creation_info{
        [mem_info](int) { return std::make_unique<CPUAllocator>(mem_info); },
        0,
        create_arena,
        l_arena_cfg};
    allocator_ptr = CreateAllocator(alloc_creation_info);
  } else {
    AllocatorCreationInfo alloc_creation_info{[mem_info](int) { return std::make_unique<CPUAllocator>(mem_info); },
                                              0, create_arena};
    allocator_ptr = CreateAllocator(alloc_creation_info);
  }
 
  std::lock_guard<std::mutex> lock{mutex_};
  return RegisterAllocatorImpl(allocator_ptr);
}
 
Status Environment::Initialize(std::unique_ptr<logging::LoggingManager> logging_manager,
                               const OrtThreadingOptions* tp_options,
                               bool create_global_thread_pools,
                               const OrtKeyValuePairs* config_entries) {
  auto status = Status::OK();
 
  logging_manager_ = std::move(logging_manager);
 
  if (config_entries != nullptr) {
    config_entries_ = *config_entries;
 
    const auto& config_map = config_entries_.Entries();
 
    if (auto iter = config_map.find(kOrtEnvAllowVirtualDevices);
        iter != config_map.end() && iter->second == "1") {
      num_allow_virtual_device_uses_ = 1;
    }
  }
 
  // create thread pools
  if (create_global_thread_pools) {
    ORT_RETURN_IF_ERROR(SetGlobalThreadingOptions(*tp_options));
  }
 
  // Initialize abseil symbolizer for readable stack traces in debug builds.
  // Restricted to Linux: InitializeSymbolizer(nullptr) relies on /proc/self/exe
  // to locate the executable, which is Linux-specific. Other platforms either
  // use a different mechanism (Windows: C++23 <stacktrace>) or would need a real
  // argv[0] path plumbed through, which is out of scope for this debug helper.
#if !defined(NDEBUG) && defined(__linux__) && !defined(__ANDROID__)
  std::call_once(symbolizerInitOnceFlag, []() {
    absl::InitializeSymbolizer(nullptr);
  });
#endif
 
  ORT_TRY {
#if !defined(ORT_MINIMAL_BUILD)
    // Register Microsoft domain with min/max op_set version as 1/1.
    std::call_once(schemaRegistrationOnceFlag, []() {
      auto& domainToVersionRangeInstance = ONNX_NAMESPACE::OpSchemaRegistry::DomainToVersionRange::Instance();
      if (domainToVersionRangeInstance.Map().find(onnxruntime::kMSDomain) == domainToVersionRangeInstance.Map().end()) {
        // External shared providers may have already added kMSDomain
        domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kMSDomain, 1, 1);
      }
      domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kMSExperimentalDomain, 1, 1);
      domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kMSNchwcDomain, 1, 1);
 
      // we have static registrations for NHWC versions of ONNX operators so this domain needs to extend to the
      // latest ONNX version
      auto onnx_version = domainToVersionRangeInstance.LastReleaseVersionMap()
                              .find(ONNX_NAMESPACE::ONNX_DOMAIN)
                              ->second;
      domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kMSInternalNHWCDomain, 1, onnx_version);
 
      domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kPytorchAtenDomain, 1, 1);
#ifdef USE_DML
      domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kMSDmlDomain, 1, 1);
#endif
// Register contributed schemas.
// The corresponding kernels are registered inside the appropriate execution provider.
#ifndef DISABLE_CONTRIB_OPS
      RegisterOpSetSchema<contrib::OpSet_Microsoft_ver1>();
      RegisterOpSetSchema<contrib::OpSet_ONNX_Deprecated>();
      // internal opset that has NHWC versions of ONNX operators
      RegisterOpSetSchema<internal_nhwc_onnx::OpSet_Internal_NHWC_ONNX>();
      contrib::RegisterContribSchemas();
#endif
 
#ifdef USE_DML
      dml::RegisterDmlSchemas();
#endif
      // ONNX registers these schemas automatically unless static registration was disabled at build time.
      if (ONNX_NAMESPACE::IsOnnxStaticRegistrationDisabled()) {
        RegisterOnnxOperatorSetSchema();
 
#ifndef DISABLE_ML_OPS
        RegisterOnnxMLOperatorSetSchema();
#endif
 
#if defined(ENABLE_TRAINING_OPS)
        RegisterOnnxTrainingOperatorSetSchema();
#endif
      }
 
#if defined(ENABLE_TRAINING_OPS)
      // preserve this order until <training schemas>: this depends on operatorsetschema registration.
      training::RegisterTrainingOpSchemas();
#endif
#ifdef ENABLE_TRAINING
      training::GradientBuilderRegistry::GetInstance().RegisterGradientBuilders();
      training::LossFunctionRegistry::GetInstance().RegisterNonOperatorLossFunctions();
      training::OptimizerBuilderRegistry::GetInstance().RegisterBuilders();
      training::OptimizerGraphBuilderRegistry::GetInstance().RegisterGraphBuilders();
      // <training schemas>
      // This was added for a partner team and is most probably no longer in use.
      // Can be removed once we have the confirmation.
      training::GraphTransformerRegistry::GetInstance().RegisterExternalGraphTransformers();
#endif
    });
 
    // Register MemCpy schema;
 
    // These ops are internal-only, so register outside of onnx
 
    std::vector<std::string> all_fixed_size_types;
 
    std::vector<std::string> all_tensor_types = OpSchema::all_tensor_types_ir9();
    std::vector<std::string> all_sequence_types = OpSchema::all_tensor_sequence_types();
    all_fixed_size_types.insert(all_fixed_size_types.end(), all_tensor_types.begin(), all_tensor_types.end());
    all_fixed_size_types.insert(all_fixed_size_types.end(), all_sequence_types.begin(), all_sequence_types.end());
    all_fixed_size_types.emplace_back("seq(tensor(bfloat16))");
    all_fixed_size_types.erase(std::remove_if(all_fixed_size_types.begin(), all_fixed_size_types.end(),
                                              [](const std::string& s) { return s.find("string") != std::string::npos; }),
                               all_fixed_size_types.end());
 
    ORT_ATTRIBUTE_UNUSED ONNX_OPERATOR_SCHEMA(MemcpyFromHost)
        .Input(0, "X", "input", "T")
        .Output(0, "Y", "output", "T")
        .TypeConstraint(
            "T",
            all_fixed_size_types,
            "Constrain to all fixed size tensor and sequence types. If the dtype attribute is not provided this must be a valid output type.")
        .TypeAndShapeInferenceFunction(propagateShapeAndTypeFromFirstInput)
        .SetDoc(R"DOC(
Internal copy node
)DOC");
 
    ORT_ATTRIBUTE_UNUSED ONNX_OPERATOR_SCHEMA(MemcpyToHost)
        .Input(0, "X", "input", "T")
        .Output(0, "Y", "output", "T")
        .TypeConstraint(
            "T",
            all_fixed_size_types,
            "Constrain to all fixed size tensor and sequence types. If the dtype attribute is not provided this must be a valid output type.")
        .TypeAndShapeInferenceFunction(propagateShapeAndTypeFromFirstInput)
        .SetDoc(R"DOC(
Internal copy node
)DOC");
 
#endif  // !defined(ORT_MINIMAL_BUILD)
    // fire off startup telemetry (this call is idempotent)
    const Env& env = Env::Default();
    env.GetTelemetryProvider().LogProcessInfo();
 
#if !defined(ORT_MINIMAL_BUILD)
    // register internal EPs for autoep selection
    ORT_RETURN_IF_ERROR(CreateAndRegisterInternalEps());
#endif
  }
  ORT_CATCH(const std::exception& ex) {
    ORT_HANDLE_EXCEPTION([&]() {
      status = Status(ONNXRUNTIME, common::RUNTIME_EXCEPTION, std::string{"Exception caught: "} + ex.what());
    });
  }
  ORT_CATCH(...) {
    status = Status{ONNXRUNTIME, common::RUNTIME_EXCEPTION};
  }
  return status;
}
 
Status Environment::SetGlobalThreadingOptions(const OrtThreadingOptions& tp_options) {
  if (create_global_thread_pools_) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Global thread pools have already been created, cannot replace them");
  }
  create_global_thread_pools_ = true;
  OrtThreadPoolParams to = tp_options.intra_op_thread_pool_params;
  if (to.name == nullptr) {
    to.name = ORT_TSTR("intra-op");
  }
  intra_op_thread_pool_ = concurrency::CreateThreadPool(&Env::Default(), to, concurrency::ThreadPoolType::INTRA_OP);
  to = tp_options.inter_op_thread_pool_params;
  if (to.name == nullptr) {
    to.name = ORT_TSTR("inter-op");
  }
  inter_op_thread_pool_ = concurrency::CreateThreadPool(&Env::Default(), to, concurrency::ThreadPoolType::INTER_OP);
  return Status::OK();
}
 
Status Environment::CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo& mem_info,
                                                 const std::unordered_map<std::string, std::string>& options,
                                                 const OrtArenaCfg* arena_cfg) {
  if (provider_type == onnxruntime::kCpuExecutionProvider) {
    ORT_UNUSED_PARAMETER(options);
    return CreateAndRegisterAllocator(mem_info, arena_cfg);
  }
 
#if defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE)
  if (provider_type == onnxruntime::kCudaExecutionProvider) {
    if (mem_info.device.MemType() == OrtDevice::MemType::HOST_ACCESSIBLE) {
      AllocatorPtr allocator_ptr = GetProviderInfo_CUDA().CreateCudaPinnedAllocator(
          static_cast<int16_t>(mem_info.device.Id()),
          arena_cfg->max_mem,
          static_cast<ArenaExtendStrategy>(arena_cfg->arena_extend_strategy),
          arena_cfg);
      return RegisterAllocatorImpl(allocator_ptr);
    } else {
      CUDAExecutionProviderInfo cuda_ep_info;
      GetProviderInfo_CUDA().CUDAExecutionProviderInfo__FromProviderOptions(options, cuda_ep_info);
      CUDAExecutionProviderExternalAllocatorInfo external_info = cuda_ep_info.external_allocator_info;
      AllocatorPtr allocator_ptr = GetProviderInfo_CUDA().CreateCudaAllocator(
          static_cast<int16_t>(mem_info.device.Id()),
          arena_cfg->max_mem,
          static_cast<ArenaExtendStrategy>(arena_cfg->arena_extend_strategy),
          external_info, arena_cfg);
      return RegisterAllocatorImpl(allocator_ptr);
    }
  }
#endif
 
  return Status{ONNXRUNTIME, common::INVALID_ARGUMENT,
                provider_type + " is not implemented in CreateAndRegisterAllocatorV2()"};
}
 
#ifdef ORT_ENABLE_SESSION_THREADPOOL_CALLBACKS
Status Environment::SetPerSessionWorkCallbacks(const OrtThreadPoolCallbacksConfig& config) {
  per_session_work_callbacks_ = config;
  return Status::OK();
}
#endif
 
Environment::~Environment() {
  // need to make sure all the OrtAllocator instances are released prior to any plugin EPs being freed.
  // this is because any entry in shared_allocators_ wrapping an OrtAllocator from a plugin EP owns the OrtAllocator
  // instance and will call Release on it. If the plugin EP has been freed the Release will fail.
  shared_allocators_.clear();
 
  // and as any OrtAllocator instances in shared_ort_allocators_ were owned by values in shared_allocators_ and have
  // now been released we need to clear that too before calling UnregisterExecutionProviderLibrary().
  shared_ort_allocators_.clear();
 
#if !defined(ORT_MINIMAL_BUILD)
  // unregister any remaining EP libraries so they're cleaned up in a determistic way.
  while (!ep_libraries_.empty()) {
    auto it = ep_libraries_.begin();
    ORT_IGNORE_RETURN_VALUE(UnregisterExecutionProviderLibrary(it->first));
  }
#endif
}
 
AllocatorPtr Environment::GetRegisteredSharedAllocator(const OrtMemoryInfo& mem_info) const {
  std::lock_guard<std::mutex> lock{mutex_};
 
  auto it = FindExistingAllocator(shared_allocators_, mem_info, /*match_name*/ false, /*ignore_alignment*/ true);
  return it != shared_allocators_.end() ? *it : nullptr;
}
 
Status Environment::GetSharedAllocator(const OrtMemoryInfo& mem_info, OrtAllocator*& allocator) {
  std::lock_guard<std::mutex> lock{mutex_};
 
  // doesn't matter whether we match a custom allocator or an EP allocator so match_name is false
  auto it = FindExistingAllocator(shared_ort_allocators_, mem_info, /*match_name*/ false);
  allocator = it != shared_ort_allocators_.end() ? *it : nullptr;
 
  // use the default CPU allocator if there's no custom or EP provided CPU allocator
  if (!allocator && (mem_info.device.Type() == OrtDevice::CPU &&
                     mem_info.device.MemType() == OrtDevice::MemType::DEFAULT)) {
    if (!default_cpu_ort_allocator_) {
      auto cpu_ort_allocator = std::make_unique<OrtAllocatorImplWrappingIAllocator>(CPUAllocator::DefaultInstance());
      default_cpu_ort_allocator_ = std::move(cpu_ort_allocator);
    }
 
    allocator = default_cpu_ort_allocator_.get();
  }
 
  return Status::OK();
}
 
OrtKeyValuePairs Environment::GetConfigEntries() const {
  std::shared_lock<std::shared_mutex> lock{config_entries_mutex_};
  return config_entries_;  // copy
}
 
void Environment::InsertOrAssignConfigEntry(std::string key, std::string value) {
  std::lock_guard<std::shared_mutex> lock{config_entries_mutex_};
  config_entries_.Add(std::move(key), std::move(value));
}
 
void Environment::RemoveConfigEntry(const std::string& key) {
  std::lock_guard<std::shared_mutex> lock{config_entries_mutex_};
  config_entries_.Remove(key.c_str());
}
 
#if !defined(ORT_MINIMAL_BUILD)
 
//
// Plugin EP support
//
 
namespace {
Status CreateDataTransferForFactory(OrtEpFactory& ep_factory,
                                    std::unique_ptr<plugin_ep::DataTransfer>& data_transfer) {
  OrtDataTransferImpl* data_transfer_impl = nullptr;
  OrtStatus* ort_status = ep_factory.CreateDataTransfer(&ep_factory, &data_transfer_impl);
  plugin_ep::OrtDataTransferImplUniquePtr owned_impl{data_transfer_impl};
 
  if (ort_status != nullptr) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, EP_FAIL,
                           "Error creating data transfer: ", ToStatusAndRelease(ort_status).ToString());
  }
 
  if (owned_impl != nullptr) {
    data_transfer = std::make_unique<plugin_ep::DataTransfer>(std::move(owned_impl));
  }
 
  return Status::OK();
}
 
bool AreVirtualDevicesAllowed(std::string_view lib_registration_name) {
  constexpr std::string_view suffix{".virtual"};
 
  return lib_registration_name.size() >= suffix.size() &&
         lib_registration_name.compare(lib_registration_name.size() - suffix.size(),
                                       suffix.size(), suffix) == 0;
}
}  // namespace
 
Status Environment::RegisterExecutionProviderLibrary(const std::string& registration_name,
                                                     std::unique_ptr<EpLibrary> ep_library,
                                                     const std::vector<EpFactoryInternal*>& internal_factories) {
#if defined(_WIN32) || defined(ORT_USE_TELEMETRY)
  const Env& env = Env::Default();
 
#if defined(ORT_USE_TELEMETRY)
  const TimePoint tp = std::chrono::high_resolution_clock::now();
#endif
 
  // Windows ETW needs these calls even without ORT_USE_TELEMETRY.
  env.GetTelemetryProvider().LogRegisterEpLibraryStart(registration_name);
#endif  // defined(_WIN32) || defined(ORT_USE_TELEMETRY)
 
  auto status = Status::OK();
 
  ORT_TRY {
    status = [&]() -> Status {
      bool registration_succeeded = false;
 
      if (ep_libraries_.contains(registration_name)) {
        return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "EP library is already registered under ", registration_name);
      }
 
      std::unique_ptr<EpInfo> ep_info;
      ORT_RETURN_IF_ERROR(EpInfo::Create(std::move(ep_library), ep_info, internal_factories));
 
      // Register shared allocators
      const size_t max_allocator_count = SafeInt<size_t>(ep_info->execution_devices.size()) * 2;
      std::vector<const OrtMemoryInfo*> registered_allocator_memory_infos;
      registered_allocator_memory_infos.reserve(max_allocator_count);
 
      auto rollback_shared_allocator_registrations = gsl::finally([&]() {
        if (registration_succeeded) {
          return;
        }
        for (auto it = registered_allocator_memory_infos.rbegin(); it != registered_allocator_memory_infos.rend(); ++it) {
          ORT_IGNORE_RETURN_VALUE(UnregisterAllocatorImpl(**it, /*error_if_not_found*/ false));
        }
      });
 
      for (const auto& ed : ep_info->execution_devices) {
        // Add shared allocators so they're available without an inference session being required. Do not replace an
        // existing allocator: we only need one for the OrtMemoryInfo and must preserve user-provided allocators.
        for (const OrtMemoryInfo* memory_info : {ed->device_memory_info, ed->host_accessible_memory_info}) {
          if (memory_info == nullptr) {
            continue;
          }
 
          OrtAllocator* registered_allocator = nullptr;
          ORT_RETURN_IF_ERROR(CreateSharedAllocatorImpl(*ed, *memory_info, OrtDeviceAllocator, nullptr,
                                                        &registered_allocator, /*replace_existing*/ false));
          if (registered_allocator != nullptr) {
            registered_allocator_memory_infos.push_back(memory_info);
          }
        }
      }
 
      // Register data transfers
      std::vector<plugin_ep::DataTransfer*> registered_data_transfers;
      registered_data_transfers.reserve(ep_info->factories.size());
      ep_info->data_transfers.reserve(ep_info->factories.size());
 
      auto rollback_data_transfer_registrations = gsl::finally([&]() {
        if (registration_succeeded) {
          return;
        }
 
        for (auto it = registered_data_transfers.rbegin(); it != registered_data_transfers.rend(); ++it) {
          ORT_IGNORE_RETURN_VALUE(data_transfer_mgr_.UnregisterDataTransfer(*it));
        }
      });
 
      for (auto* factory : ep_info->factories) {
        std::unique_ptr<plugin_ep::DataTransfer> data_transfer;
        ORT_RETURN_IF_ERROR(CreateDataTransferForFactory(*factory, data_transfer));
 
        if (data_transfer) {
          auto* data_transfer_ptr = data_transfer.get();
          ORT_RETURN_IF_ERROR(data_transfer_mgr_.RegisterDataTransfer(std::move(data_transfer)));
          registered_data_transfers.push_back(data_transfer_ptr);
          ep_info->data_transfers.push_back(data_transfer_ptr);
        }
      }
 
      // Register internal factories
      std::vector<EpFactoryInternal*> registered_internal_factories;
      registered_internal_factories.reserve(internal_factories.size());
 
      auto rollback_internal_factory_registration = gsl::finally([&]() {
        if (registration_succeeded) {
          return;
        }
 
        for (auto it = registered_internal_factories.rbegin(); it != registered_internal_factories.rend(); ++it) {
          internal_ep_factories_.erase(*it);
        }
      });
 
      for (auto* internal_factory : internal_factories) {
        if (internal_ep_factories_.insert(internal_factory).second) {
          registered_internal_factories.push_back(internal_factory);
        }
      }
 
      // Register EP devices
      auto rollback_execution_devices_registration = gsl::finally(
          [&, original_size = execution_devices_.size()]() {
            if (registration_succeeded) {
              return;
            }
 
            execution_devices_.erase(execution_devices_.begin() + original_size,
                                     execution_devices_.end());
          });
 
      execution_devices_.reserve(SafeInt<size_t>(execution_devices_.size()) +
                                 ep_info->execution_devices.size());
      std::transform(ep_info->execution_devices.begin(), ep_info->execution_devices.end(),
                     std::back_inserter(execution_devices_),
                     [](const std::unique_ptr<OrtEpDevice>& ep_device) {
                       return ep_device.get();
                     });
 
      // Finally, register the EP library
 
      // Notes:
      // `ep_info`'s target must stay alive for any rollback logic that may need to run.
      // Directly moving into `ep_libraries_.emplace()` could cause it to be prematurely destroyed if emplace throws
      // after ownership has transferred from `ep_info`. This is why we first emplace an empty unique_ptr and then
      // swap into it.
      //
      // We ignore `emplace_result.second` since we already checked for an existing entry in `ep_libraries_` above.
      const auto emplace_result = ep_libraries_.emplace(registration_name, nullptr);
      emplace_result.first->second.swap(ep_info);
 
      registration_succeeded = true;
      return Status::OK();
    }();
  }
  ORT_CATCH(const std::exception& ex) {
    ORT_HANDLE_EXCEPTION([&]() {
      status = ORT_MAKE_STATUS(ONNXRUNTIME, FAIL,
                               "Failed to register EP library under '", registration_name, "' with error: ", ex.what());
    });
  }
  ORT_CATCH(...) {
    ORT_HANDLE_EXCEPTION([&]() {
      status = ORT_MAKE_STATUS(ONNXRUNTIME, FAIL,
                               "Failed to register EP library under '", registration_name, "' with unknown exception.");
    });
  }
 
#if defined(ORT_USE_TELEMETRY)
  env.GetTelemetryProvider().LogRegisterEpLibraryEnd(registration_name, status, TimeDiffMicroSeconds(tp));
#elif defined(_WIN32)
  env.GetTelemetryProvider().LogRegisterEpLibraryEnd(registration_name, status, 0);
#endif
  return status;
}
 
Status Environment::CreateAndRegisterInternalEps() {
  // Capture allow_virtual_devices here (lock-free) and pass it to the internal EP factories at
  // construction. The internal WebGPU EP factory needs it in GetSupportedDevices but cannot query the
  // OrtEnv singleton there: internal EPs are registered from Environment::Create, before OrtEnv
  // publishes p_instance_, so there is no instance to find.
  const bool allow_virtual_devices = num_allow_virtual_device_uses_ > 0;
  auto internal_ep_libraries = EpLibraryInternal::CreateInternalEps(allow_virtual_devices);
  for (auto& ep_library : internal_ep_libraries) {
    // we do a std::move in the function call so need a valid pointer for the args after the move
    auto* internal_library_ptr = ep_library.get();
    ORT_RETURN_IF_ERROR(RegisterExecutionProviderLibrary(internal_library_ptr->RegistrationName(),
                                                         std::move(ep_library),
                                                         {&internal_library_ptr->GetInternalFactory()}));
  }
 
  return Status::OK();
}
 
Status Environment::CreateAndRegisterStaticPluginEps(StaticPluginEpRegistrationToken) {
  // Intentionally does not take mutex_ and calls the private, non-locking RegisterExecutionProviderLibrary overload.
  // This is safe because the caller holds the OrtEnv creation mutex, so no other thread can obtain a reference to this
  // Environment yet. Taking mutex_ here would deadlock if a plugin EP called a locking Environment API from
  // OrtEpFactory::GetSupportedDevices.
  auto static_plugin_ep_libraries = CreateStaticPluginEpLibraries();
  for (auto& ep_library : static_plugin_ep_libraries) {
    const std::string registration_name = ep_library->RegistrationName();
    ORT_RETURN_IF_ERROR(RegisterExecutionProviderLibrary(registration_name, std::move(ep_library)));
  }
 
  return Status::OK();
}
 
Status Environment::RegisterExecutionProviderLibrary(const std::string& registration_name, const ORTCHAR_T* lib_path) {
  std::lock_guard<std::mutex> lock{mutex_};
 
#if defined(_WIN32) || defined(ORT_USE_TELEMETRY)
  std::string lib_file_name = PathToUTF8String(std::filesystem::path(lib_path).filename().native());
  Env::Default().GetTelemetryProvider().LogRegisterEpLibraryWithLibPath(registration_name, lib_file_name);
#endif
 
  std::vector<EpFactoryInternal*> internal_factories;
  std::unique_ptr<EpLibrary> ep_library;
 
  // An application can allow EP libraries to create virtual devices by using an EP library registration name that
  // ends in the suffix ".virtual". If so, ORT automatically sets the config key "allow_virtual_devices" to "1"
  // in the environment. We track the number of libraries that use virtual devices to be able to remove
  // "allow_virtual_devices" from the config entries when the last library is unregistered. In practice,
  // we expect only one such library to be registered for cross-compilation.
  if (AreVirtualDevicesAllowed(registration_name)) {
    if (num_allow_virtual_device_uses_ == 0) {
      InsertOrAssignConfigEntry(kOrtEnvAllowVirtualDevices, "1");
    }
 
    num_allow_virtual_device_uses_ += 1;
  }
 
  // This will create an EpLibraryPlugin or an EpLibraryProviderBridge depending on what the library supports.
  ORT_RETURN_IF_ERROR(LoadPluginOrProviderBridge(registration_name, lib_path, ep_library, internal_factories));
 
  return RegisterExecutionProviderLibrary(registration_name, std::move(ep_library), internal_factories);
}
 
Status Environment::UnregisterExecutionProviderLibrary(const std::string& registration_name) {
  std::lock_guard<std::mutex> lock{mutex_};
 
  if (ep_libraries_.count(registration_name) == 0) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Execution provider library: ", registration_name,
                           " was not registered.");
  }
 
  auto status = Status::OK();
 
  ORT_TRY {
    auto ep_info = std::move(ep_libraries_[registration_name]);
 
    // Clean up environment config entry that may have been added to enable virtual devices.
    if (AreVirtualDevicesAllowed(registration_name)) {
      num_allow_virtual_device_uses_ -= 1;
 
      if (num_allow_virtual_device_uses_ == 0) {
        RemoveConfigEntry(kOrtEnvAllowVirtualDevices);
      }
    }
 
    // remove from map and global list of OrtEpDevice* before unloading so we don't get a leftover entry if
    // something goes wrong in any of the following steps..
    ep_libraries_.erase(registration_name);
 
    for (auto* data_transfer : ep_info->data_transfers) {
      ORT_RETURN_IF_ERROR(data_transfer_mgr_.UnregisterDataTransfer(data_transfer));
    }
 
    for (auto* internal_factory : ep_info->internal_factories) {
      internal_ep_factories_.erase(internal_factory);
    }
 
    for (const auto& ed : ep_info->execution_devices) {
      // remove from global list of OrtEpDevices
      if (auto it = std::find(execution_devices_.begin(), execution_devices_.end(), ed.get());
          it != execution_devices_.end()) {
        execution_devices_.erase(it);
      }
 
      // unregister any shared allocators.
      // match only the OrtEpDevice allocator in case the user registered a custom allocator with matching info.
      const bool error_if_not_found = false;
      if (ed->device_memory_info != nullptr) {
        ORT_RETURN_IF_ERROR(UnregisterAllocatorImpl(*ed->device_memory_info, error_if_not_found));
      }
 
      if (ed->host_accessible_memory_info != nullptr) {
        ORT_RETURN_IF_ERROR(UnregisterAllocatorImpl(*ed->host_accessible_memory_info, error_if_not_found));
      }
    }
 
    ep_info.reset();
  }
  ORT_CATCH(const std::exception& ex) {
    ORT_HANDLE_EXCEPTION([&]() {
      status = ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Failed to unregister EP library: ", registration_name,
                               " with error: ", ex.what());
    });
  }
 
  return status;
}
 
Status Environment::GetHardwareDeviceEpIncompatibilityDetails(
    const std::string& ep_name,
    const OrtHardwareDevice* hw,
    std::unique_ptr<OrtDeviceEpIncompatibilityDetails>& details) const {
  std::lock_guard<std::mutex> lock{mutex_};
 
  OrtEpFactory* matched_factory = nullptr;
 
  // Search for a factory whose GetName() matches ep_name exactly.
  for (const auto& [registration_name, ep_info] : ep_libraries_) {
    for (OrtEpFactory* factory : ep_info->factories) {
      if (factory != nullptr && factory->GetName != nullptr) {
        const char* factory_name = factory->GetName(factory);
        if (factory_name != nullptr && ep_name == factory_name) {
          matched_factory = factory;
          break;
        }
      }
    }
    if (matched_factory != nullptr) {
      break;
    }
  }
 
  if (matched_factory == nullptr) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                           "No valid factory found for execution provider '", ep_name, "'.");
  }
 
  // ORT creates the details object with default values (compatible)
  details = std::make_unique<OrtDeviceEpIncompatibilityDetails>();
  // If the factory implements GetHardwareDeviceIncompatibilityDetails, let it initialize the details
  if (matched_factory->GetHardwareDeviceIncompatibilityDetails != nullptr) {
    OrtStatusPtr status = matched_factory->GetHardwareDeviceIncompatibilityDetails(matched_factory, hw, details.get());
 
    if (status != nullptr) {
      return ToStatusAndRelease(status);
    }
  }
 
  // Factory doesn't implement the hook - details remain with default values (compatible)
  return Status::OK();
}
 
namespace {
std::vector<const OrtHardwareDevice*> SortDevicesByType() {
  auto& devices = DeviceDiscovery::GetDevices();
  std::vector<const OrtHardwareDevice*> sorted_devices;
  sorted_devices.reserve(devices.size());
 
  const auto select_by_type = [&](OrtHardwareDeviceType type) {
    for (const auto& device : devices) {
      if (device.type == type) {
        sorted_devices.push_back(&device);
      }
    }
  };
 
  select_by_type(OrtHardwareDeviceType_NPU);
  select_by_type(OrtHardwareDeviceType_GPU);
  select_by_type(OrtHardwareDeviceType_CPU);
 
  return sorted_devices;
}
 
// Returns a static reference to sorted hardware devices.
// Hardware devices are discovered once at startup and don't change.
const std::vector<const OrtHardwareDevice*>& GetSortedHardwareDevices() {
  static const auto sorted_devices = SortDevicesByType();
  return sorted_devices;
}
}  // namespace
 
const std::vector<const OrtHardwareDevice*>& Environment::GetSortedOrtHardwareDevices() const {
  return GetSortedHardwareDevices();
}
 
Status Environment::CreateSharedAllocator(const OrtEpDevice& ep_device,
                                          OrtDeviceMemoryType mem_type, OrtAllocatorType allocator_type,
                                          const OrtKeyValuePairs* allocator_options,
                                          OrtAllocator** allocator_out) {
  auto* memory_info = mem_type == OrtDeviceMemoryType_DEFAULT ? ep_device.device_memory_info
                                                              : ep_device.host_accessible_memory_info;
  if (memory_info == nullptr) {
    return Status(ONNXRUNTIME, ORT_INVALID_ARGUMENT, "Invalid memory type for OrtEpDevice.");
  }
 
  std::lock_guard<std::mutex> lock{mutex_};
  return CreateSharedAllocatorImpl(ep_device, *memory_info, allocator_type, allocator_options, allocator_out,
                                   /*replace_existing*/ true);
}
 
Status Environment::CreateSharedAllocatorImpl(const OrtEpDevice& ep_device,
                                              const OrtMemoryInfo& memory_info,
                                              OrtAllocatorType allocator_type,
                                              const OrtKeyValuePairs* allocator_options,
                                              OrtAllocator** allocator_out,
                                              bool replace_existing) {
  // NOTE: memory_info is guaranteed to come from the OrtEpDevice when this is called
 
  if (allocator_type == OrtAllocatorType::OrtArenaAllocator) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL,
                           "OrtAllocatorType::OrtArenaAllocator is reserved for ONNX Runtime internal usage only. "
                           "The EP implements arena support internally so please use OrtDeviceAllocator and provide "
                           "any arena options via the allocator options.");
  }
 
  // we only want one shared allocator for an OrtDevice in the shared_allocators_ so that it's deterministic which
  // one will be used for an inference session. ignore the name so that is the case.
  auto existing_ort_allocator =
      FindExistingAllocator(shared_ort_allocators_, memory_info, /*match_name*/ true);
 
  auto existing_shared_allocator =
      FindExistingAllocator(shared_allocators_, memory_info, /*match_name*/ false);
 
  if (!replace_existing &&
      (existing_ort_allocator != shared_ort_allocators_.end() ||
       existing_shared_allocator != shared_allocators_.end())) {
    if (allocator_out != nullptr) {
      *allocator_out = nullptr;
    }
 
    LOGS_DEFAULT(INFO) << "A shared allocator is already registered for " << memory_info
                       << ". Skipping EP allocator creation.";
    return Status::OK();
  }
 
  // we need to remove from shared_ort_allocators_ first in case the entry in shared_allocators_ owns the pointer in
  // shared_ort_allocators_.
  if (existing_ort_allocator != shared_ort_allocators_.end()) {
    shared_ort_allocators_.erase(existing_ort_allocator);
  }
 
  if (existing_shared_allocator != shared_allocators_.end()) {
    shared_allocators_.erase(existing_shared_allocator);
  }
 
  // Create a new allocator.
 
  auto* ep_factory = ep_device.ep_factory;
  OrtAllocator* raw_ort_allocator = nullptr;
  AllocatorPtr shared_allocator;
  ORT_RETURN_IF_ERROR(ep_allocator_utils::CreateAndWrapEpAllocator(*ep_factory, memory_info, allocator_options,
                                                                   shared_allocator, &raw_ort_allocator));
  ORT_RETURN_IF_NOT(raw_ort_allocator != nullptr, "OrtEpFactory returned a null allocator.");
 
  shared_allocators_.reserve(SafeInt<size_t>(shared_allocators_.size()) + 1);
  const auto [_, inserted] = shared_ort_allocators_.insert(raw_ort_allocator);
  ORT_RETURN_IF_NOT(inserted, "OrtEpFactory returned an allocator that is already registered.");
  shared_allocators_.push_back(std::move(shared_allocator));
 
  if (allocator_out != nullptr) {
    *allocator_out = raw_ort_allocator;
  }
 
  return Status::OK();
}
 
Status Environment::ReleaseSharedAllocator(const OrtEpDevice& ep_device, OrtDeviceMemoryType mem_type) {
  auto* memory_info = mem_type == OrtDeviceMemoryType_DEFAULT ? ep_device.device_memory_info
                                                              : ep_device.host_accessible_memory_info;
  if (memory_info == nullptr) {
    return Status(ONNXRUNTIME, ORT_INVALID_ARGUMENT, "Invalid memory type for OrtEpDevice.");
  }
 
  auto status = UnregisterAllocator(*memory_info);
 
  return status;
}
 
Status Environment::EpInfo::Create(std::unique_ptr<EpLibrary> library_in, std::unique_ptr<EpInfo>& out,
                                   const std::vector<EpFactoryInternal*>& internal_factories) {
  if (!library_in) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "EpLibrary was null");
  }
 
  auto instance_unique_ptr = std::unique_ptr<EpInfo>(new EpInfo());  // can't use make_unique with private ctor
  EpInfo& instance = *instance_unique_ptr;
  instance.library = std::move(library_in);
  instance.internal_factories = internal_factories;
 
  ORT_RETURN_IF_ERROR(instance.library->Load());
 
  {
    auto factories = instance.library->GetFactories();
    instance.factories.assign(factories.begin(), factories.end());
  }
 
  // OrtHardwareDevice instances to pass to GetSupportedDevices.
  const auto& sorted_devices = GetSortedHardwareDevices();
 
  for (auto* factory_ptr : instance.factories) {
    ORT_ENFORCE(factory_ptr != nullptr, "Factory pointer was null. EpLibrary should prevent this. Library:",
                instance.library->RegistrationName());
 
    auto& factory = *factory_ptr;
 
    std::array<OrtEpDevice*, 8> ep_devices{nullptr};
    size_t num_ep_devices = 0;
    ORT_RETURN_IF_ERROR(ToStatusAndRelease(
        factory.GetSupportedDevices(&factory, sorted_devices.data(), sorted_devices.size(),
                                    ep_devices.data(), ep_devices.size(), &num_ep_devices)));
 
    const auto* library_path = instance.library->LibraryPath();
    for (size_t i = 0; i < num_ep_devices; ++i) {
      if (ep_devices[i] != nullptr) {  // should never happen but just in case...
        if (library_path != nullptr) {
          // Add library path to EP metadata if available.
          // This is used by GenAI for custom library loading so we want to consistently set it.
          ep_devices[i]->ep_metadata.Add(kOrtEpDevice_EpMetadataKey_LibraryPath, library_path->string());
        }
 
        instance.execution_devices.emplace_back(ep_devices[i]);  // take ownership
      }
    }
  }
 
  out = std::move(instance_unique_ptr);
  return Status::OK();
}
 
Environment::EpInfo::~EpInfo() {
  execution_devices.clear();
  auto status = library->Unload();
  if (!status.IsOK()) {
    LOGS_DEFAULT(WARNING) << "Failed to unload EP library registered under '" << library->RegistrationName()
                          << "' with error: " << status.ErrorMessage();
  }
}
 
#endif  // !defined(ORT_MINIMAL_BUILD)
 
}  // namespace onnxruntime