2
2
Contains code for loggers that help visualize the information from each modifier
3
3
"""
4
4
5
- import logging
6
5
import os
7
6
import time
8
7
import warnings
9
8
from abc import ABC
9
+ from loguru import logger
10
10
from contextlib import contextmanager
11
11
from datetime import datetime
12
- from logging import CRITICAL , DEBUG , ERROR , INFO , WARN , Logger
13
12
from pathlib import Path
14
13
from types import ModuleType
15
14
from typing import Any , Callable , Dict , List , Optional , Union
52
51
"WANDBLogger" ,
53
52
"SparsificationGroupLogger" ,
54
53
"LoggerManager" ,
55
- "LOGGING_LEVELS" ,
56
54
]
57
55
ALL_TOKEN = "__ALL__"
58
- LOGGING_LEVELS = {
59
- "debug" : DEBUG ,
60
- "info" : INFO ,
61
- "warn" : WARN ,
62
- "error" : ERROR ,
63
- "critical" : CRITICAL ,
64
- }
65
56
DEFAULT_TAG = "defaul_tag"
66
57
67
58
@@ -231,7 +222,7 @@ def lambda_func(
231
222
def log_hyperparams (
232
223
self ,
233
224
params : Dict ,
234
- level : Optional [int ] = None ,
225
+ level : Optional [Union [ int , str ] ] = None ,
235
226
) -> bool :
236
227
"""
237
228
:param params: Each key-value pair in the dictionary is the name of the
@@ -256,7 +247,7 @@ def log_scalar(
256
247
value : float ,
257
248
step : Optional [int ] = None ,
258
249
wall_time : Optional [float ] = None ,
259
- level : Optional [int ] = None ,
250
+ level : Optional [Union [ int , str ] ] = None ,
260
251
) -> bool :
261
252
"""
262
253
:param tag: identifying tag to log the value with
@@ -285,7 +276,7 @@ def log_scalars(
285
276
values : Dict [str , float ],
286
277
step : Optional [int ] = None ,
287
278
wall_time : Optional [float ] = None ,
288
- level : Optional [int ] = None ,
279
+ level : Optional [Union [ int , str ] ] = None ,
289
280
) -> bool :
290
281
"""
291
282
:param tag: identifying tag to log the values with
@@ -313,40 +304,28 @@ class PythonLogger(LambdaLogger):
313
304
"""
314
305
Modifier metrics that handles printing values into a python metrics instance.
315
306
316
- :param logger: a metrics instance to log to, if None then will create it's own
317
- :param log_level: default level to log any incoming data at on the logging.Logger
318
- instance when an explicit log level isn't provided
319
307
:param name: name given to the metrics, used for identification;
320
308
defaults to python
321
309
:param enabled: True to log, False otherwise
322
310
"""
323
311
312
+ # Class-level variable to track if file sink is created
313
+ _global_file_sink_id = None
314
+
324
315
def __init__ (
325
316
self ,
326
- logger : Logger = None ,
327
- log_level : int = None ,
328
317
name : str = "python" ,
329
318
enabled : bool = True ,
330
319
):
331
- self ._logger = logger or self . _create_default_logger (log_level = log_level )
320
+ self ._create_default_logger ()
332
321
333
322
super ().__init__ (
334
323
lambda_func = self ._log_lambda ,
335
324
name = name ,
336
325
enabled = enabled ,
337
326
)
338
327
339
- def __getattr__ (self , item ):
340
- return getattr (self ._logger , item )
341
-
342
- @property
343
- def logger (self ) -> Logger :
344
- """
345
- :return: a metrics instance to log to, if None then will create it's own
346
- """
347
- return self ._logger
348
-
349
- def _create_default_logger (self , log_level : Optional [int ] = None ) -> logging .Logger :
328
+ def _create_default_logger (self ) -> None :
350
329
"""
351
330
Create a default modifier metrics,
352
331
with a file handler logging at the debug level
@@ -355,24 +334,9 @@ def _create_default_logger(self, log_level: Optional[int] = None) -> logging.Log
355
334
:param log_level: logging level for the console metrics
356
335
:return: metrics
357
336
"""
358
- logger = logging .getLogger (__name__ )
359
-
360
- # Console handler, for logging high level modifier logs
361
- # must be created before the file handler
362
- # as file handler is also a stream handler
363
- if not any (
364
- isinstance (handler , logging .StreamHandler ) for handler in logger .handlers
365
- ):
366
- stream_handler = logging .StreamHandler ()
367
- stream_handler .setLevel (
368
- log_level or logging .getLogger ("llmcompressor" ).level
369
- )
370
- logger .addHandler (stream_handler )
371
337
372
338
# File handler setup, for logging modifier debug statements
373
- if not any (
374
- isinstance (handler , logging .FileHandler ) for handler in logger .handlers
375
- ):
339
+ if PythonLogger ._global_file_sink_id is None :
376
340
base_log_path = (
377
341
os .environ .get ("NM_TEST_LOG_DIR" )
378
342
if os .environ .get ("NM_TEST_MODE" )
@@ -382,27 +346,19 @@ def _create_default_logger(self, log_level: Optional[int] = None) -> logging.Log
382
346
dt_string = now .strftime ("%d-%m-%Y_%H.%M.%S" )
383
347
log_path = os .path .join (base_log_path , f"{ dt_string } .log" )
384
348
os .makedirs (base_log_path , exist_ok = True )
385
- file_handler = logging .FileHandler (
386
- log_path ,
387
- delay = True ,
349
+ PythonLogger ._global_file_sink_id = logger .add (
350
+ log_path , level = "DEBUG" , delay = True
388
351
)
389
- file_handler .setLevel (LOGGING_LEVELS ["debug" ])
390
- logger .addHandler (file_handler )
391
352
logger .info (f"Logging all LLM Compressor modifier-level logs to { log_path } " )
392
353
393
- logger .setLevel (LOGGING_LEVELS ["debug" ])
394
- logger .propagate = False
395
-
396
- return logger
397
-
398
354
def _log_lambda (
399
355
self ,
400
356
tag : Optional [str ],
401
357
value : Optional [Union [float , str ]],
402
358
values : Optional [Dict [str , float ]],
403
359
step : Optional [int ],
404
360
wall_time : Optional [float ],
405
- level : Optional [int ] = None ,
361
+ level : Optional [Union [ int , str ] ] = None ,
406
362
) -> bool :
407
363
"""
408
364
:param tag: identifying tag to log the values with
@@ -415,9 +371,11 @@ def _log_lambda(
415
371
:return: True if logged, False otherwise.
416
372
"""
417
373
if not level :
418
- level = LOGGING_LEVELS [ "debug" ]
374
+ level = "DEBUG"
419
375
420
- if level > LOGGING_LEVELS ["debug" ]:
376
+ if (isinstance (level , int ) and level > logger .level ("DEBUG" ).no ) or (
377
+ isinstance (level , str ) and logger .level (level ).no > logger .level ("DEBUG" ).no
378
+ ):
421
379
if step is not None :
422
380
format = "%s %s step %s: %s"
423
381
log_args = [
@@ -433,7 +391,7 @@ def _log_lambda(
433
391
format = "%s %s [%s - %s]: %s"
434
392
log_args = [self .name , tag , step , wall_time , values or value ]
435
393
436
- self . _logger .log (level , format , * log_args )
394
+ logger .log (level , format , * log_args )
437
395
438
396
return True
439
397
@@ -443,7 +401,7 @@ def log_string(
443
401
string : Optional [str ],
444
402
step : Optional [int ],
445
403
wall_time : Optional [float ] = None ,
446
- level : Optional [int ] = None ,
404
+ level : Optional [Union [ int , str ] ] = None ,
447
405
) -> bool :
448
406
"""
449
407
:param tag: identifying tag to log the values with
@@ -540,7 +498,7 @@ def _log_lambda(
540
498
values : Optional [Dict [str , float ]],
541
499
step : Optional [int ],
542
500
wall_time : Optional [float ],
543
- level : Optional [int ] = None ,
501
+ level : Optional [Union [ int , str ] ] = None ,
544
502
) -> bool :
545
503
if value is not None :
546
504
self ._writer .add_scalar (tag , value , step , wall_time )
@@ -614,7 +572,7 @@ def _log_lambda(
614
572
values : Optional [Dict [str , float ]],
615
573
step : Optional [int ],
616
574
wall_time : Optional [float ],
617
- level : Optional [int ] = None ,
575
+ level : Optional [Union [ int , str ] ] = None ,
618
576
) -> bool :
619
577
params = {}
620
578
@@ -656,11 +614,10 @@ class SparsificationGroupLogger(BaseLogger):
656
614
:param lambda_func: an optional lambda function to call back into with any logs.
657
615
The expected call sequence is (tag, value, values, step, wall_time) -> bool
658
616
The return type is True if logged and False otherwise.
659
- :param python: an optional argument for logging to a python metrics.
660
- May be a logging.Logger instance to log to, True to create a metrics instance,
661
- or non truthy to not log anything (False, None)
617
+ :param python: an bool argument for logging to a python metrics.
618
+ True to create a metrics instance, or False to not log anything
662
619
:param python_log_level: if python,
663
- the level to log any incoming data at on the logging.Logger instance
620
+ the level to log any incoming data at on the loguru.logger instance
664
621
:param tensorboard: an optional argument for logging to a tensorboard writer.
665
622
May be a SummaryWriter instance to log to, a string representing the directory
666
623
to create a new SummaryWriter to log to, True to create a new SummaryWriter,
@@ -688,8 +645,8 @@ def __init__(
688
645
bool ,
689
646
]
690
647
] = None ,
691
- python : Optional [ Union [ bool , Logger ]] = None ,
692
- python_log_level : int = logging . INFO ,
648
+ python : bool = False ,
649
+ python_log_level : Optional [ Union [ int , str ]] = " INFO" ,
693
650
tensorboard : Optional [Union [bool , str , SummaryWriter ]] = None ,
694
651
wandb_ : Optional [Union [bool , Dict ]] = None ,
695
652
name : str = "sparsification" ,
@@ -706,8 +663,6 @@ def __init__(
706
663
if python :
707
664
self ._loggers .append (
708
665
PythonLogger (
709
- logger = python if isinstance (python , Logger ) else None ,
710
- log_level = python_log_level ,
711
666
name = name ,
712
667
enabled = enabled ,
713
668
)
@@ -751,7 +706,7 @@ def loggers(self) -> List[BaseLogger]:
751
706
"""
752
707
return self ._loggers
753
708
754
- def log_hyperparams (self , params : Dict , level : Optional [int ] = None ):
709
+ def log_hyperparams (self , params : Dict , level : Optional [Union [ int , str ] ] = None ):
755
710
"""
756
711
:param params: Each key-value pair in the dictionary is the name of the
757
712
hyper parameter and it's corresponding value.
@@ -765,7 +720,7 @@ def log_scalar(
765
720
value : float ,
766
721
step : Optional [int ] = None ,
767
722
wall_time : Optional [float ] = None ,
768
- level : Optional [int ] = None ,
723
+ level : Optional [Union [ int , str ] ] = None ,
769
724
):
770
725
"""
771
726
:param tag: identifying tag to log the value with
@@ -783,7 +738,7 @@ def log_scalars(
783
738
values : Dict [str , float ],
784
739
step : Optional [int ] = None ,
785
740
wall_time : Optional [float ] = None ,
786
- level : Optional [int ] = None ,
741
+ level : Optional [Union [ int , str ] ] = None ,
787
742
):
788
743
"""
789
744
:param tag: identifying tag to log the values with
@@ -956,7 +911,7 @@ def log_scalar(
956
911
step : Optional [int ] = None ,
957
912
wall_time : Optional [float ] = None ,
958
913
log_types : Union [str , List [str ]] = ALL_TOKEN ,
959
- level : Optional [int ] = None ,
914
+ level : Optional [Union [ int , str ] ] = None ,
960
915
):
961
916
"""
962
917
(Note: this method is deprecated and will be removed in a future version,
@@ -986,7 +941,7 @@ def log_scalars(
986
941
step : Optional [int ] = None ,
987
942
wall_time : Optional [float ] = None ,
988
943
log_types : Union [str , List [str ]] = ALL_TOKEN ,
989
- level : Optional [int ] = None ,
944
+ level : Optional [Union [ int , str ] ] = None ,
990
945
):
991
946
"""
992
947
(Note: this method is deprecated and will be removed in a future version,
@@ -1013,7 +968,7 @@ def log_hyperparams(
1013
968
self ,
1014
969
params : Dict ,
1015
970
log_types : Union [str , List [str ]] = ALL_TOKEN ,
1016
- level : Optional [int ] = None ,
971
+ level : Optional [Union [ int , str ] ] = None ,
1017
972
):
1018
973
"""
1019
974
(Note: this method is deprecated and will be removed in a future version,
@@ -1036,7 +991,7 @@ def log_string(
1036
991
step : Optional [int ] = None ,
1037
992
wall_time : Optional [float ] = None ,
1038
993
log_types : Union [str , List [str ]] = ALL_TOKEN ,
1039
- level : Optional [int ] = None ,
994
+ level : Optional [Union [ int , str ] ] = None ,
1040
995
):
1041
996
"""
1042
997
(Note: this method is deprecated and will be removed in a future version,
@@ -1119,7 +1074,7 @@ def log_string(
1119
1074
step : Optional [int ] = None ,
1120
1075
wall_time : Optional [float ] = None ,
1121
1076
log_types : Union [str , List [str ]] = ALL_TOKEN ,
1122
- level : Optional [int ] = None ,
1077
+ level : Optional [Union [ int , str ] ] = None ,
1123
1078
):
1124
1079
"""
1125
1080
:param tag: identifying tag to log the values with
@@ -1151,7 +1106,7 @@ def debug(self, tag, string, *args, **kwargs):
1151
1106
:param kwargs: additional arguments to pass to the metrics,
1152
1107
see `log_string` for more details
1153
1108
"""
1154
- kwargs ["level" ] = logging . DEBUG
1109
+ kwargs ["level" ] = " DEBUG"
1155
1110
self .log_string (tag = tag , string = string , * args , ** kwargs )
1156
1111
1157
1112
def info (self , tag , string , * args , ** kwargs ):
@@ -1166,7 +1121,7 @@ def info(self, tag, string, *args, **kwargs):
1166
1121
:param kwargs: additional arguments to pass to the metrics,
1167
1122
see `log_string` for more details
1168
1123
"""
1169
- kwargs ["level" ] = logging . INFO
1124
+ kwargs ["level" ] = " INFO"
1170
1125
self .log_string (tag = tag , string = string , * args , ** kwargs )
1171
1126
1172
1127
def warning (self , tag , string , * args , ** kwargs ):
@@ -1181,7 +1136,7 @@ def warning(self, tag, string, *args, **kwargs):
1181
1136
:param kwargs: additional arguments to pass to the metrics,
1182
1137
see `log_string` for more details
1183
1138
"""
1184
- kwargs ["level" ] = logging . WARNING
1139
+ kwargs ["level" ] = " WARNING"
1185
1140
self .log_string (tag = tag , string = string , * args , ** kwargs )
1186
1141
1187
1142
def warn (self , tag , string , * args , ** kwargs ):
@@ -1204,7 +1159,7 @@ def error(self, tag, string, *args, **kwargs):
1204
1159
:param kwargs: additional arguments to pass to the metrics,
1205
1160
see `log_string` for more details
1206
1161
"""
1207
- kwargs ["level" ] = logging . ERROR
1162
+ kwargs ["level" ] = " ERROR"
1208
1163
self .log_string (tag = tag , string = string , * args , ** kwargs )
1209
1164
1210
1165
def critical (self , tag , string , * args , ** kwargs ):
@@ -1219,7 +1174,7 @@ def critical(self, tag, string, *args, **kwargs):
1219
1174
:param kwargs: additional arguments to pass to the metrics,
1220
1175
see `log_string` for more details
1221
1176
"""
1222
- kwargs ["level" ] = logging . CRITICAL
1177
+ kwargs ["level" ] = " CRITICAL"
1223
1178
self .log_string (tag = tag , string = string , * args , ** kwargs )
1224
1179
1225
1180
@@ -1232,7 +1187,7 @@ def log_hyperparams(
1232
1187
self ,
1233
1188
params : Dict ,
1234
1189
log_types : Union [str , List [str ]] = ALL_TOKEN ,
1235
- level : Optional [int ] = None ,
1190
+ level : Optional [Union [ int , str ] ] = None ,
1236
1191
):
1237
1192
"""
1238
1193
:param params: Each key-value pair in the dictionary is the name of the
@@ -1249,7 +1204,7 @@ def log_scalar(
1249
1204
step : Optional [int ] = None ,
1250
1205
wall_time : Optional [float ] = None ,
1251
1206
log_types : Union [str , List [str ]] = ALL_TOKEN ,
1252
- level : Optional [int ] = None ,
1207
+ level : Optional [Union [ int , str ] ] = None ,
1253
1208
):
1254
1209
"""
1255
1210
:param tag: identifying tag to log the value with
@@ -1276,7 +1231,7 @@ def log_scalars(
1276
1231
step : Optional [int ] = None ,
1277
1232
wall_time : Optional [float ] = None ,
1278
1233
log_types : Union [str , List [str ]] = ALL_TOKEN ,
1279
- level : Optional [int ] = None ,
1234
+ level : Optional [Union [ int , str ] ] = None ,
1280
1235
):
1281
1236
"""
1282
1237
:param tag: identifying tag to log the values with
0 commit comments