File size: 56,808 Bytes
c6535db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import time
import torch
import threading
from ..comfy_copy.res4lyf_sampling import get_res4lyf_step_with_model
import comfy.sample
from .log import print_step_timing
from .skip import _parse_hs_mode, parse_skip_indices_config
from .extrapolation import SigmaAwareHistory, set_sigma_target, set_current_x
from .samplers.euler import sample_step_euler
from .samplers.res2m import sample_step_res_2m
from .samplers.res2s import sample_step_res_2s
from .samplers.ddim import sample_step_ddim
from .samplers.dpmpp_2m import sample_step_dpmpp_2m
from .samplers.dpmpp_2s import sample_step_dpmpp_2s
from .samplers.lms import sample_step_lms
from .samplers.res_multistep import sample_step_res_multistep
from .samplers.res_multistep_official import sample_step_res_multistep_official
from .samplers.res_multistep_ancestral import sample_step_res_multistep_ancestral
from .samplers.heun import sample_step_heun
from .samplers.gradient_estimation import sample_step_gradient_estimation


# Thread-local storage for metadata (to pass out of ksampler_function without breaking ComfyUI)
_thread_local = threading.local()


def detect_model_type(model_patcher, verbose=False):
    """
    Enhanced model type detection that identifies specific models like Qwen, SDXL, Flux, etc.

    Args:
        model_patcher: ComfyUI ModelPatcher object
        verbose: Print debug information during detection

    Returns:
        str: Detected model type identifier (e.g., "qwen-image", "sdxl-base", "flux-dev")
    """
    try:
        # Get the model class name as fallback
        class_name = "unknown"
        if hasattr(model_patcher, 'model') and hasattr(model_patcher.model, '__class__'):
            class_name = model_patcher.model.__class__.__name__.lower()
            if verbose:
                print(f"[FSampler] Model class name: {class_name}")

        # Check model_patcher attributes for checkpoint info
        checkpoint_info = []
        for attr in ['checkpoint_path', 'model_name', 'filename', 'name']:
            if hasattr(model_patcher, attr):
                val = getattr(model_patcher, attr)
                if val:
                    checkpoint_info.append(str(val).lower())
                    if verbose:
                        print(f"[FSampler] Found {attr}: {val}")

        # Check checkpoint info for Qwen patterns
        checkpoint_str = ' '.join(checkpoint_info)
        if 'qwen' in checkpoint_str:
            if verbose:
                print(f"[FSampler] Found 'qwen' in checkpoint info: {checkpoint_str}")
            if 'edit' in checkpoint_str:
                if '2509' in checkpoint_str:
                    return "qwen-image-edit-2509"
                return "qwen-image-edit"
            return "qwen-image"

        # Check for checkpoint filename (most reliable for Qwen detection)
        checkpoint_name = ""
        if hasattr(model_patcher, 'model') and hasattr(model_patcher.model, 'model_config'):
            config = model_patcher.model.model_config
            if verbose:
                print(f"[FSampler] Model has config, checking unet_config...")
            if hasattr(config, 'unet_config') and isinstance(config.unet_config, dict):
                # Check config for model-specific markers
                unet_config = config.unet_config
                if verbose:
                    print(f"[FSampler] unet_config keys: {list(unet_config.keys())[:10]}")

                # Qwen detection via config
                unet_str = str(unet_config).lower()
                if 'qwen' in unet_str:
                    if verbose:
                        print(f"[FSampler] Found 'qwen' in unet_config")
                    if 'edit' in unet_str:
                        if '2509' in unet_str:
                            return "qwen-image-edit-2509"
                        return "qwen-image-edit"
                    return "qwen-image"

        # Check model state dict keys for Qwen-specific patterns
        if hasattr(model_patcher, 'model') and hasattr(model_patcher.model, 'state_dict'):
            try:
                state_dict_keys = list(model_patcher.model.state_dict().keys())
                keys_str = ' '.join(state_dict_keys[:20]).lower()  # Check first 20 keys
                if verbose:
                    print(f"[FSampler] First state dict keys: {state_dict_keys[:5]}")

                if 'qwen' in keys_str:
                    if verbose:
                        print(f"[FSampler] Found 'qwen' in state_dict keys")
                    if 'edit' in keys_str:
                        return "qwen-image-edit"
                    return "qwen-image"
            except:
                pass

        # Check for common model architecture patterns
        # SDXL detection
        if 'sdxl' in class_name:
            if 'refiner' in class_name:
                return "sdxl-refiner"
            return "sdxl-base"

        # Flux detection
        if 'flux' in class_name:
            if 'schnell' in class_name:
                return "flux-schnell"
            elif 'pro' in class_name:
                return "flux-pro"
            return "flux-dev"

        # SD3 detection
        if 'sd3' in class_name or 'stable_diffusion_3' in class_name:
            if 'turbo' in class_name:
                return "sd3-large-turbo"
            elif 'large' in class_name:
                return "sd3-large"
            return "sd3-medium"

        # Cascade detection
        if 'cascade' in class_name:
            if 'stage_c' in class_name or 'stagec' in class_name:
                return "cascade-stage-c"
            elif 'stage_b' in class_name or 'stageb' in class_name:
                return "cascade-stage-b"
            return "cascade-stage-a"

        # Hunyuan detection
        if 'hunyuan' in class_name:
            if 'video' in class_name:
                return "hunyuan-video"
            return "hunyuan-dit"

        # Kolors detection
        if 'kolors' in class_name:
            return "kolors"

        # PixArt detection
        if 'pixart' in class_name:
            if 'sigma' in class_name:
                return "pixart-sigma"
            return "pixart-alpha"

        # Playground detection
        if 'playground' in class_name:
            if 'v2.5' in class_name or 'v25' in class_name:
                return "playground-v25"
            return "playground-v2"

        # AuraFlow detection
        if 'auraflow' in class_name:
            return "auraflow"

        # CogView detection
        if 'cogview' in class_name:
            return "cogview3"

        # Cosmos detection
        if 'cosmos' in class_name:
            return "cosmos-1"

        # Lumina detection
        if 'lumina' in class_name:
            return "lumina-next"

        # SD 1.x/2.x detection (fallback)
        if 'sd' in class_name or 'stablediffusion' in class_name:
            if '2.1' in class_name or 'v2_1' in class_name:
                return "sd21"
            elif '2.0' in class_name or 'v2_0' in class_name or 'v2' in class_name:
                return "sd20"
            return "sd15"

        # Return class name as fallback
        return class_name if class_name != "unknown" else "unknown"

    except Exception as e:
        print(f"[FSampler] Model detection error: {e}")
        return "unknown"


def create_fsampler_ksampler(sampler="euler", adaptive_mode="none",
                              smoothing_beta=0.9, skip_mode="none", add_noise_ratio=0.0,
                              add_noise_type="whitened", scheduler=None, start_at_step=None,
                              end_at_step=None, denoise=None, debug=False,
                              protect_last_steps=4, protect_first_steps=2,
                              anchor_interval=None, max_consecutive_skips=None,
                              use_no_grad=True, official_comfy=False, skip_indices: str = "",
                              seed=None, timestamp_start=None, sigma_aware=False,
                              extrapolate_denoised=False):
    """Create a KSAMPLER with FSampler's skip-aware sampling logic.

    Returns a comfy.samplers.KSAMPLER that can be used with comfy.sample.sample_custom()
    or guider.sample() for the modular SamplerCustomAdvanced workflow.
    """

    def ksampler_function(model, x, sigmas, extra_args=None, callback=None, disable=None):
        # Allow runtime control of autograd to match official behavior
        import contextlib, torch as _torch
        ctx = _torch.no_grad() if use_no_grad else contextlib.nullcontext()

        with ctx:
            extra_args = {} if extra_args is None else extra_args
            s_in = x.new_ones([x.shape[0]])
            error_history = []          # RES2M denoised history (REAL + SKIPPED)
            epsilon_history = SigmaAwareHistory() if (sigma_aware or extrapolate_denoised) else []  # REAL-only epsilon history for extrapolation + learning
            sigma_previous = None
            smoothed_error_ratio = 1.0  # For RES2M Phase-1 adaptive weights
            learning_ratio = 1.0        # Universal learning stabilizer

            # Initialize metadata tracking (when debug=True)
            per_step_data = [] if debug else None
            l_history = [] if debug else None

            # Normalize predictor selection using history from skip_mode (hN/sK or legacy aliases)
            _skip_mode_l = str(skip_mode).lower() if isinstance(skip_mode, str) else "none"
            hs = _parse_hs_mode(_skip_mode_l)
            if hs is not None:
                history_order, _ = hs
                if history_order >= 4:
                    predictor_type = "h4"
                elif history_order == 3:
                    predictor_type = "richardson"
                else:
                    predictor_type = "linear"
            else:
                if _skip_mode_l in ("h4", ):  # 4-point predictor
                    predictor_type = "h4"
                elif _skip_mode_l in ("h3", "richardson"):
                    predictor_type = "richardson"
                else:
                    predictor_type = "linear"

            skip_stats = {
                "total_steps": 0,
                "model_calls": 0,
                "skipped": 0,
                # Adaptive skip controller state
                "consecutive_skips": 0,
                "last_anchor_step": -1,
                # Explicit indices gating state
                "explicit_streak": False,
                "needed_learns": 2,
            }

            if debug:
                print(f"\n{'='*60}")
                print(f"FSampler Settings:")
                print(f"  sampler: {sampler}")
                if scheduler is not None:
                    print(f"  scheduler: {scheduler}")
                print(f"  adaptive_mode: {adaptive_mode}")
                print(f"  smoothing_beta: {smoothing_beta}")
            print(f"  skip_mode: {skip_mode}")
            print(f"  add_noise_ratio: {add_noise_ratio}")
            print(f"  noise_type: {add_noise_type}")
            print(f"  official_comfy: {official_comfy}")
            print(f"  sigma_aware: {sigma_aware}")
            print(f"  extrapolate_denoised: {extrapolate_denoised}")
            if skip_mode != "none":
                print(f"  protect_first_steps: {protect_first_steps}")
                print(f"  protect_last_steps: {protect_last_steps}")
            if denoise is not None:
                print(f"  denoise: {denoise}")
                if start_at_step is not None:
                    print(f"  start_at_step: {start_at_step}")
                if end_at_step is not None:
                    print(f"  end_at_step: {end_at_step}")
            print(f"  steps: {len(sigmas)-1}")
            try:
                import torch as _torch
                s = sigmas
                if isinstance(s, _torch.Tensor):
                    s0 = float(s[0]); sL = float(s[-1])
                    f3 = [float(v) for v in s[:3]]
                    l3 = [float(v) for v in s[-3:]]
                else:
                    s0 = float(s[0]); sL = float(s[-1])
                    f3 = [float(v) for v in s[:3]]
                    l3 = [float(v) for v in s[-3:]]
                print(f"  sigma_range: [{s0:.4f}, {sL:.4f}] len={len(s)}")
                print(f"  sigmas head: {[round(v,4) for v in f3]} tail: {[round(v,4) for v in l3]}")
            except Exception:
                pass
                print(f"{'='*60}\n")

            # Parse explicit skip indices early (indices bounded once total_steps is known)
            explicit_predictor, explicit_indices = parse_skip_indices_config(skip_indices or "")
            explicit_mode = len(explicit_indices) > 0

            res2m_prev_was_skipped = False
            res2m_noise_cooldown = 0
            res2m_prev_sigma_down = None
            resms_prev_sigma_down = None
            _t_start = time.time()
            total_steps = len(sigmas) - 1
            # Determine effective modes and bound explicit indices
            if explicit_mode:
                # Bound and filter per-total-steps; also ensure we never include 0/1
                explicit_indices = {i for i in explicit_indices if 0 <= i < total_steps and i >= 2}
                if len(explicit_indices) == 0:
                    explicit_mode = False
            effective_skip_mode = ("none" if explicit_mode else skip_mode)
            effective_adaptive_mode = ("none" if explicit_mode else adaptive_mode)
            if explicit_mode:
                # Override predictor used for learning/hints
                predictor_type = explicit_predictor
                if debug:
                    print(f"Explicit Skip Mode: ON")
                    print(f"  explicit_predictor: {explicit_predictor}")
                    print(f"  explicit_indices: {sorted(list(explicit_indices))}")
                    print(f"  disabled: skip_mode/adaptive/anchor/max_consecutive/protect_*")
            for step_index in range(total_steps):
                sigma_current = sigmas[step_index]
                sigma_next = sigmas[step_index + 1]

                print_step_timing(sampler, step_index, _t_start, total_steps)

                # Track total steps centrally for all samplers
                skip_stats["total_steps"] += 1

                # Capture step start time and model_calls before step (for metadata)
                step_start_time = time.time() if debug else None
                model_calls_before = skip_stats.get("model_calls", 0) if debug else None

                # Set sigma context for sigma-aware extrapolation
                if sigma_aware:
                    epsilon_history.set_pending_sigma(float(sigma_current))
                    set_sigma_target(float(sigma_current))

                # Set denoised context for denoised-mode extrapolation
                if extrapolate_denoised:
                    epsilon_history.set_pending_x(x)
                    set_current_x(x)

                if sampler == "res_2m":
                    x, smoothed_error_ratio, learning_ratio, res2m_prev_was_skipped, res2m_noise_cooldown, res2m_prev_sigma_down = sample_step_res_2m(
                        model=model,
                        noisy_latent=x,
                        sigma_current=sigma_current,
                        sigma_next=sigma_next,
                        sigma_previous=sigma_previous,
                        s_in=s_in,
                        extra_args=extra_args,
                        error_history=error_history,
                        epsilon_history=epsilon_history,
                        prev_was_skipped=res2m_prev_was_skipped,
                        step_index=step_index,
                        total_steps=total_steps,
                        adaptive_mode=effective_adaptive_mode,
                        smoothing_beta=smoothing_beta,
                        smoothed_error_ratio=smoothed_error_ratio,
                        learning_ratio=learning_ratio,
                        predictor_type=predictor_type,
                        add_noise_ratio=add_noise_ratio,
                        add_noise_type=add_noise_type,
                        skip_mode=effective_skip_mode,
                        skip_stats=skip_stats,
                        protect_last_steps=protect_last_steps,
                        debug=debug,
                        protect_first_steps=protect_first_steps,
                        anchor_interval=anchor_interval,
                        max_consecutive_skips=max_consecutive_skips,
                        noise_cooldown=res2m_noise_cooldown,
                        old_sigma_down=res2m_prev_sigma_down,
                    )
                elif sampler == "res_2s":
                    x, learning_ratio = sample_step_res_2s(
                        model=model,
                        noisy_latent=x,
                        sigma_current=sigma_current,
                        sigma_next=sigma_next,
                        s_in=s_in,
                        extra_args=extra_args,
                        epsilon_history=epsilon_history,
                        learning_ratio=learning_ratio,
                        smoothing_beta=smoothing_beta,
                        predictor_type=predictor_type,
                        step_index=step_index,
                        total_steps=total_steps,
                        add_noise_ratio=add_noise_ratio,
                        add_noise_type=add_noise_type,
                        debug=debug,
                        skip_mode=effective_skip_mode,
                        skip_stats=skip_stats,
                        protect_last_steps=protect_last_steps,
                        protect_first_steps=protect_first_steps,
                        anchor_interval=anchor_interval,
                        max_consecutive_skips=max_consecutive_skips,
                        explicit_skip_indices=(explicit_indices if explicit_mode else None),
                        explicit_predictor=(explicit_predictor if explicit_mode else None),
                    )
                elif sampler == "euler":
                    x, learning_ratio = sample_step_euler(
                        model=model,
                        noisy_latent=x,
                        sigma_current=sigma_current,
                        sigma_next=sigma_next,
                        s_in=s_in,
                        extra_args=extra_args,
                        epsilon_history=epsilon_history,
                        learning_ratio=learning_ratio,
                        smoothing_beta=smoothing_beta,
                        predictor_type=predictor_type,
                        step_index=step_index,
                        total_steps=total_steps,
                        add_noise_ratio=add_noise_ratio,
                        add_noise_type=add_noise_type,
                        skip_mode=effective_skip_mode,
                        skip_stats=skip_stats,
                        protect_last_steps=protect_last_steps,
                        debug=debug,
                        protect_first_steps=protect_first_steps,
                        anchor_interval=anchor_interval,
                        max_consecutive_skips=max_consecutive_skips,
                        official_comfy=official_comfy,
                        adaptive_mode=effective_adaptive_mode,
                        explicit_skip_indices=(explicit_indices if explicit_mode else None),
                        explicit_predictor=(explicit_predictor if explicit_mode else None),
                    )
                elif sampler == "ddim":
                    x, learning_ratio = sample_step_ddim(
                        model=model,
                        noisy_latent=x,
                        sigma_current=sigma_current,
                        sigma_next=sigma_next,
                        s_in=s_in,
                        extra_args=extra_args,
                        epsilon_history=epsilon_history,
                        learning_ratio=learning_ratio,
                        smoothing_beta=smoothing_beta,
                        predictor_type=predictor_type,
                        step_index=step_index,
                        total_steps=total_steps,
                        add_noise_ratio=add_noise_ratio,
                        add_noise_type=add_noise_type,
                        skip_mode=effective_skip_mode,
                        skip_stats=skip_stats,
                        protect_last_steps=protect_last_steps,
                        debug=debug,
                        protect_first_steps=protect_first_steps,
                        anchor_interval=anchor_interval,
                        max_consecutive_skips=max_consecutive_skips,
                        official_comfy=official_comfy,
                        adaptive_mode=effective_adaptive_mode,
                        explicit_skip_indices=(explicit_indices if explicit_mode else None),
                        explicit_predictor=(explicit_predictor if explicit_mode else None),
                    )
                elif sampler == "dpmpp_2m":
                    x, learning_ratio = sample_step_dpmpp_2m(
                        model=model,
                        noisy_latent=x,
                        sigma_current=sigma_current,
                        sigma_next=sigma_next,
                        sigma_previous=sigma_previous,
                        s_in=s_in,
                        extra_args=extra_args,
                        epsilon_history=epsilon_history,
                        learning_ratio=learning_ratio,
                        smoothing_beta=smoothing_beta,
                        predictor_type=predictor_type,
                        step_index=step_index,
                        total_steps=total_steps,
                        add_noise_ratio=add_noise_ratio,
                        add_noise_type=add_noise_type,
                        skip_mode=effective_skip_mode,
                        skip_stats=skip_stats,
                        protect_last_steps=protect_last_steps,
                        debug=debug,
                        protect_first_steps=protect_first_steps,
                        anchor_interval=anchor_interval,
                        max_consecutive_skips=max_consecutive_skips,
                        official_comfy=official_comfy,
                        adaptive_mode=effective_adaptive_mode,
                        explicit_skip_indices=(explicit_indices if explicit_mode else None),
                        explicit_predictor=(explicit_predictor if explicit_mode else None),
                    )
                elif sampler == "dpmpp_2s":
                    x, learning_ratio = sample_step_dpmpp_2s(
                        model=model,
                        noisy_latent=x,
                        sigma_current=sigma_current,
                        sigma_next=sigma_next,
                        s_in=s_in,
                        extra_args=extra_args,
                        epsilon_history=epsilon_history,
                        learning_ratio=learning_ratio,
                        smoothing_beta=smoothing_beta,
                        predictor_type=predictor_type,
                        step_index=step_index,
                        total_steps=total_steps,
                        add_noise_ratio=add_noise_ratio,
                        add_noise_type=add_noise_type,
                        skip_mode=effective_skip_mode,
                        skip_stats=skip_stats,
                        protect_last_steps=protect_last_steps,
                        debug=debug,
                        protect_first_steps=protect_first_steps,
                        anchor_interval=anchor_interval,
                        max_consecutive_skips=max_consecutive_skips,
                        official_comfy=official_comfy,
                        explicit_skip_indices=(explicit_indices if explicit_mode else None),
                        explicit_predictor=(explicit_predictor if explicit_mode else None),
                    )
                elif sampler == "lms":
                    x, learning_ratio = sample_step_lms(
                        model=model,
                        noisy_latent=x,
                        sigma_current=sigma_current,
                        sigma_next=sigma_next,
                        sigma_previous=sigma_previous,
                        s_in=s_in,
                        extra_args=extra_args,
                        epsilon_history=epsilon_history,
                        learning_ratio=learning_ratio,
                        smoothing_beta=smoothing_beta,
                        predictor_type=predictor_type,
                        step_index=step_index,
                        total_steps=total_steps,
                        add_noise_ratio=add_noise_ratio,
                        add_noise_type=add_noise_type,
                        skip_mode=effective_skip_mode,
                        skip_stats=skip_stats,
                        protect_last_steps=protect_last_steps,
                        debug=debug,
                        protect_first_steps=protect_first_steps,
                        anchor_interval=anchor_interval,
                        max_consecutive_skips=max_consecutive_skips,
                        official_comfy=official_comfy,
                        adaptive_mode=effective_adaptive_mode,
                        explicit_skip_indices=(explicit_indices if explicit_mode else None),
                        explicit_predictor=(explicit_predictor if explicit_mode else None),
                    )
                elif sampler == "heun":
                    x, learning_ratio = sample_step_heun(
                        model=model,
                        noisy_latent=x,
                        sigma_current=sigma_current,
                        sigma_next=sigma_next,
                        s_in=s_in,
                        extra_args=extra_args,
                        epsilon_history=epsilon_history,
                        learning_ratio=learning_ratio,
                        smoothing_beta=smoothing_beta,
                        predictor_type=predictor_type,
                        step_index=step_index,
                        total_steps=total_steps,
                        add_noise_ratio=add_noise_ratio,
                        add_noise_type=add_noise_type,
                        skip_mode=effective_skip_mode,
                        skip_stats=skip_stats,
                        protect_last_steps=protect_last_steps,
                        debug=debug,
                        protect_first_steps=protect_first_steps,
                        anchor_interval=anchor_interval,
                        max_consecutive_skips=max_consecutive_skips,
                        official_comfy=official_comfy,
                        adaptive_mode=effective_adaptive_mode,
                        explicit_skip_indices=(explicit_indices if explicit_mode else None),
                        explicit_predictor=(explicit_predictor if explicit_mode else None),
                    )
                elif sampler == "gradient_estimation":
                    x, learning_ratio = sample_step_gradient_estimation(
                        model=model,
                        noisy_latent=x,
                        sigma_current=sigma_current,
                        sigma_next=sigma_next,
                        sigma_previous=sigma_previous,
                        s_in=s_in,
                        extra_args=extra_args,
                        epsilon_history=epsilon_history,
                        learning_ratio=learning_ratio,
                        smoothing_beta=smoothing_beta,
                        predictor_type=predictor_type,
                        step_index=step_index,
                        total_steps=total_steps,
                        add_noise_ratio=add_noise_ratio,
                        add_noise_type=add_noise_type,
                        skip_mode=effective_skip_mode,
                        skip_stats=skip_stats,
                        protect_last_steps=protect_last_steps,
                        debug=debug,
                        protect_first_steps=protect_first_steps,
                        anchor_interval=anchor_interval,
                        max_consecutive_skips=max_consecutive_skips,
                        official_comfy=official_comfy,
                        explicit_skip_indices=(explicit_indices if explicit_mode else None),
                        explicit_predictor=(explicit_predictor if explicit_mode else None),
                    )
                elif sampler == "res_multistep":
                    # Choose official vs res4lyf implementation
                    if official_comfy:
                        try:
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep_official(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                                adaptive_mode=effective_adaptive_mode,
                                explicit_skip_indices=(explicit_indices if explicit_mode else None),
                                explicit_predictor=(explicit_predictor if explicit_mode else None),
                            )
                        except TypeError:
                            # Back-compat with older function signature
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep_official(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                            )
                    else:
                        try:
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                                adaptive_mode=effective_adaptive_mode,
                                explicit_skip_indices=(explicit_indices if explicit_mode else None),
                                explicit_predictor=(explicit_predictor if explicit_mode else None),
                            )
                        except TypeError:
                            # Back-compat with older function signature
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                            )
                elif sampler == "res_multistep_ancestral":
                    # Dedicated ancestral variant; always call the wrapper and continue
                    x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep_ancestral(
                        model=model,
                        noisy_latent=x,
                        sigma_current=sigma_current,
                        sigma_next=sigma_next,
                        sigma_previous=sigma_previous,
                        old_sigma_down=resms_prev_sigma_down,
                        s_in=s_in,
                        extra_args=extra_args,
                        error_history=error_history,
                        epsilon_history=epsilon_history,
                        step_index=step_index,
                        total_steps=total_steps,
                        learning_ratio=learning_ratio,
                        smoothing_beta=smoothing_beta,
                        predictor_type=predictor_type,
                        add_noise_ratio=add_noise_ratio,
                        add_noise_type=add_noise_type,
                        skip_mode=effective_skip_mode,
                        skip_stats=skip_stats,
                        debug=debug,
                        protect_last_steps=protect_last_steps,
                        protect_first_steps=protect_first_steps,
                        anchor_interval=anchor_interval,
                        max_consecutive_skips=max_consecutive_skips,
                        official_comfy=official_comfy,
                        adaptive_mode=effective_adaptive_mode,
                        explicit_skip_indices=(explicit_indices if explicit_mode else None),
                        explicit_predictor=(explicit_predictor if explicit_mode else None),
                    )
                    continue
                    if official_comfy:
                        try:
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep_official(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                                adaptive_mode=effective_adaptive_mode,
                                explicit_skip_indices=(explicit_indices if explicit_mode else None),
                                explicit_predictor=(explicit_predictor if explicit_mode else None),
                            )
                        except TypeError:
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep_official(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                                adaptive_mode=effective_adaptive_mode,
                            )
                    # else (removed duplicate)
                        try:
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                                adaptive_mode=effective_adaptive_mode,
                                explicit_skip_indices=(explicit_indices if explicit_mode else None),
                                explicit_predictor=(explicit_predictor if explicit_mode else None),
                            )
                        except TypeError:
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                                adaptive_mode=effective_adaptive_mode,
                            )
                        except TypeError:
                            # Back-compat with older function signature
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep_official(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                            )
                    else:
                        try:
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                                adaptive_mode=effective_adaptive_mode,
                                explicit_skip_indices=(explicit_indices if explicit_mode else None),
                                explicit_predictor=(explicit_predictor if explicit_mode else None),
                            )
                        except TypeError:
                            # Back-compat with older function signature
                            x, learning_ratio, resms_prev_sigma_down = sample_step_res_multistep(
                                model=model,
                                noisy_latent=x,
                                sigma_current=sigma_current,
                                sigma_next=sigma_next,
                                sigma_previous=sigma_previous,
                                old_sigma_down=resms_prev_sigma_down,
                                s_in=s_in,
                                extra_args=extra_args,
                                error_history=error_history,
                                epsilon_history=epsilon_history,
                                step_index=step_index,
                                total_steps=total_steps,
                                learning_ratio=learning_ratio,
                                smoothing_beta=smoothing_beta,
                                predictor_type=predictor_type,
                                add_noise_ratio=add_noise_ratio,
                                add_noise_type=add_noise_type,
                                skip_mode=effective_skip_mode,
                                skip_stats=skip_stats,
                                debug=debug,
                                protect_last_steps=protect_last_steps,
                                protect_first_steps=protect_first_steps,
                                anchor_interval=anchor_interval,
                                max_consecutive_skips=max_consecutive_skips,
                                adaptive_mode=effective_adaptive_mode,
                            )

                # Track per-step metadata (when debug=True)
                if debug and per_step_data is not None:
                    step_end_time = time.time()
                    l_history.append(float(learning_ratio))

                    # Determine if this step was skipped by checking if model_calls increased
                    model_calls_after = skip_stats.get("model_calls", 0)
                    was_skipped = 1 if model_calls_after == model_calls_before else 0

                    per_step_data.append({
                        "step_index": step_index,
                        "sigma_current": float(sigma_current),
                        "sigma_next": float(sigma_next),
                        "was_skipped": was_skipped,
                        "learning_ratio": float(learning_ratio),
                        "step_time_seconds": step_end_time - step_start_time if step_start_time else 0.0,
                    })

                sigma_previous = sigma_current

                if callback is not None:
                    callback({'x': x, 'i': step_index, 'sigma': sigma_current, 'sigma_next': sigma_next, 'denoised': x})

            if debug and (effective_skip_mode != "none" or explicit_mode):
                total = skip_stats["total_steps"]
                called = skip_stats["model_calls"]
                skipped = skip_stats["skipped"]
                if total > 0:
                    skip_percent = (skipped / total) * 100
                    print(f"\n{'='*60}")
                    print(f"Skip Statistics:")
                    print(f"  Total steps: {total}")
                    print(f"  Model calls: {called}")
                    print(f"  Skipped: {skipped}")
                    print(f"  Reduction: {skip_percent:.1f}%")
                    print(f"{'='*60}\n")

            # Build metadata dict (when debug=True) and store in thread-local
            if debug and per_step_data is not None:
                _t_end = time.time()

                # Detect model type from model_patcher using enhanced detection
                model_type = detect_model_type(model, verbose=True)
                print(f"[FSampler Debug] Detected model type: {model_type}")

                metadata = {
                    "seed": seed,
                    "timestamp_start": timestamp_start if timestamp_start is not None else _t_start,
                    "timestamp_end": _t_end,
                    "model_type": model_type,
                    "sampler": sampler,
                    "scheduler": scheduler if scheduler else "unknown",
                    "skip_mode": skip_mode,
                    "adaptive_mode": adaptive_mode,
                    "smoothing_beta": smoothing_beta,
                    "total_steps": skip_stats["total_steps"],
                    "model_calls": skip_stats["model_calls"],
                    "skipped": skip_stats["skipped"],
                    "reduction_percent": (skip_stats["skipped"] / skip_stats["total_steps"] * 100) if skip_stats["total_steps"] > 0 else 0.0,
                    "total_time_seconds": _t_end - _t_start,
                    "protect_first_steps": protect_first_steps,
                    "protect_last_steps": protect_last_steps,
                    "anchor_interval": anchor_interval if adaptive_mode != "none" else None,
                    "max_consecutive_skips": max_consecutive_skips if adaptive_mode != "none" else None,
                    "l_final": float(learning_ratio),
                    "l_mean": sum(l_history) / len(l_history) if l_history else 1.0,
                    "l_min": min(l_history) if l_history else 1.0,
                    "l_max": max(l_history) if l_history else 1.0,
                    "per_step_data": per_step_data,
                }
                # Store in thread-local storage
                _thread_local.last_run_metadata = metadata
            else:
                _thread_local.last_run_metadata = {}

            # Return just x (not tuple) to keep ComfyUI's sampler code happy
            return x

    from comfy.samplers import KSAMPLER
    return KSAMPLER(ksampler_function)


def sample_fsampler(model_patcher, noise, sigmas, positive_conditioning, negative_conditioning,
                    cfg_scale, latent_image, sampler="euler", adaptive_mode="none",
                    smoothing_beta=0.9, skip_mode="none", add_noise_ratio=0.0, add_noise_type="whitened",
                    scheduler=None, start_at_step=None, end_at_step=None, denoise=None,
                    debug=False, callback=None, protect_last_steps=4, protect_first_steps=2,
                    anchor_interval=None, max_consecutive_skips=None, use_no_grad=True,
                    official_comfy=False, skip_indices: str = "", seed=None, timestamp_start=None,
                    sigma_aware=False, extrapolate_denoised=False):
    """Orchestrates sampling with pluggable samplers and shared skip/learning/timing.

    Uses create_fsampler_ksampler() to build a skip-aware KSAMPLER, then runs it
    through comfy.sample.sample_custom() with CFG guiding.
    """
    wrapped_sampler = create_fsampler_ksampler(
        sampler=sampler, adaptive_mode=adaptive_mode, smoothing_beta=smoothing_beta,
        skip_mode=skip_mode, add_noise_ratio=add_noise_ratio, add_noise_type=add_noise_type,
        scheduler=scheduler, start_at_step=start_at_step, end_at_step=end_at_step,
        denoise=denoise, debug=debug, protect_last_steps=protect_last_steps,
        protect_first_steps=protect_first_steps, anchor_interval=anchor_interval,
        max_consecutive_skips=max_consecutive_skips, use_no_grad=use_no_grad,
        official_comfy=official_comfy, skip_indices=skip_indices,
        seed=seed, timestamp_start=timestamp_start, sigma_aware=sigma_aware,
        extrapolate_denoised=extrapolate_denoised,
    )

    samples = comfy.sample.sample_custom(
        model=model_patcher,
        noise=noise,
        cfg=cfg_scale,
        sampler=wrapped_sampler,
        sigmas=sigmas,
        positive=positive_conditioning,
        negative=negative_conditioning,
        latent_image=latent_image,
        noise_mask=None,
        callback=callback,
        disable_pbar=False,
        seed=None
    )

    # Retrieve metadata from thread-local storage
    metadata = getattr(_thread_local, 'last_run_metadata', {})

    return samples, metadata