-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprojetoo_content.txt
5390 lines (4446 loc) · 196 KB
/
projetoo_content.txt
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
Project Structure:
├── Memoraith/
│ ├── problems.py
│ ├── setup.py
│ ├── testdata.py
│ ├── .git/
│ │ ├── hooks/
│ │ ├── info/
│ │ ├── logs/
│ │ │ ├── refs/
│ │ │ │ ├── heads/
│ │ │ │ ├── remotes/
│ │ │ │ │ ├── origin/
│ │ ├── objects/
│ │ │ ├── 01/
│ │ │ ├── 04/
│ │ │ ├── 08/
│ │ │ ├── 09/
│ │ │ ├── 0a/
│ │ │ ├── 0b/
│ │ │ ├── 0d/
│ │ │ ├── 0e/
│ │ │ ├── 13/
│ │ │ ├── 15/
│ │ │ ├── 19/
│ │ │ ├── 1b/
│ │ │ ├── 1f/
│ │ │ ├── 20/
│ │ │ ├── 25/
│ │ │ ├── 28/
│ │ │ ├── 2b/
│ │ │ ├── 30/
│ │ │ ├── 34/
│ │ │ ├── 35/
│ │ │ ├── 37/
│ │ │ ├── 39/
│ │ │ ├── 3b/
│ │ │ ├── 41/
│ │ │ ├── 43/
│ │ │ ├── 47/
│ │ │ ├── 49/
│ │ │ ├── 4a/
│ │ │ ├── 4e/
│ │ │ ├── 4f/
│ │ │ ├── 50/
│ │ │ ├── 53/
│ │ │ ├── 5f/
│ │ │ ├── 60/
│ │ │ ├── 62/
│ │ │ ├── 66/
│ │ │ ├── 6b/
│ │ │ ├── 6d/
│ │ │ ├── 6e/
│ │ │ ├── 70/
│ │ │ ├── 73/
│ │ │ ├── 74/
│ │ │ ├── 77/
│ │ │ ├── 78/
│ │ │ ├── 7a/
│ │ │ ├── 7b/
│ │ │ ├── 7c/
│ │ │ ├── 7d/
│ │ │ ├── 80/
│ │ │ ├── 85/
│ │ │ ├── 8c/
│ │ │ ├── 8e/
│ │ │ ├── 90/
│ │ │ ├── 93/
│ │ │ ├── 96/
│ │ │ ├── 98/
│ │ │ ├── 9f/
│ │ │ ├── a0/
│ │ │ ├── a3/
│ │ │ ├── a9/
│ │ │ ├── ad/
│ │ │ ├── b2/
│ │ │ ├── b4/
│ │ │ ├── b9/
│ │ │ ├── bc/
│ │ │ ├── bf/
│ │ │ ├── c0/
│ │ │ ├── c4/
│ │ │ ├── c7/
│ │ │ ├── c8/
│ │ │ ├── cd/
│ │ │ ├── d7/
│ │ │ ├── d9/
│ │ │ ├── da/
│ │ │ ├── dc/
│ │ │ ├── de/
│ │ │ ├── e1/
│ │ │ ├── e6/
│ │ │ ├── e8/
│ │ │ ├── e9/
│ │ │ ├── f0/
│ │ │ ├── f1/
│ │ │ ├── f3/
│ │ │ ├── f5/
│ │ │ ├── f7/
│ │ │ ├── f8/
│ │ │ ├── fa/
│ │ │ ├── fc/
│ │ │ ├── ff/
│ │ │ ├── info/
│ │ │ ├── pack/
│ │ ├── refs/
│ │ │ ├── heads/
│ │ │ ├── remotes/
│ │ │ │ ├── origin/
│ │ │ ├── tags/
│ ├── .github/
│ │ ├── workflows/
│ ├── .idea/
│ │ ├── inspectionProfiles/
│ ├── .pytest_cache/
│ │ ├── v/
│ │ │ ├── cache/
│ ├── dist/
│ ├── examples/
│ │ ├── example_pytorch.py
│ │ ├── example_tensorflow.py
│ ├── memoraith/
│ │ ├── cli.py
│ │ ├── config.py
│ │ ├── exceptions.py
│ │ ├── logging_config.py
│ │ ├── profiler.py
│ │ ├── __init__.py
│ │ ├── analysis/
│ │ │ ├── analyzer.py
│ │ │ ├── anomaly_detection.py
│ │ │ ├── bottleneck.py
│ │ │ ├── metrics.py
│ │ │ ├── recommendations.py
│ │ │ ├── __init__.py
│ │ │ ├── __pycache__/
│ │ ├── data_collection/
│ │ │ ├── cpu_memory.py
│ │ │ ├── gpu_memory.py
│ │ │ ├── network_memory_system.py
│ │ │ ├── resource_lock.py
│ │ │ ├── time_tracking.py
│ │ │ ├── __init__.py
│ │ │ ├── __pycache__/
│ │ ├── integration/
│ │ │ ├── common_utils.py
│ │ │ ├── framework_adapter.py
│ │ │ ├── pytorch_adapter.py
│ │ │ ├── tensorflow_adapter.py
│ │ │ ├── __init__.py
│ │ │ ├── __pycache__/
│ │ ├── reporting/
│ │ │ ├── console_report.py
│ │ │ ├── export_utils.py
│ │ │ ├── report_generator.py
│ │ │ ├── __init__.py
│ │ │ ├── __pycache__/
│ │ ├── templates/
│ │ ├── visualization/
│ │ │ ├── heatmap.py
│ │ │ ├── interactive_dashboard.py
│ │ │ ├── plot_memory.py
│ │ │ ├── plot_time.py
│ │ │ ├── real_time_visualizer.py
│ │ │ ├── __init__.py
│ │ │ ├── __pycache__/
│ │ ├── __pycache__/
│ ├── memoraith.egg-info/
│ ├── memoraith_reports/
│ │ ├── memoraith_exports/
│ ├── __pycache__/
================================================================================
File: C:\Users\PC\Desktop\Leo-Major\Memoraith\problems.py
import os
import subprocess
import json
from pathlib import Path
def run_pylint(project_dir):
"""
Runs pylint on the specified project directory and returns the JSON output.
"""
try:
# Run pylint with JSON output
result = subprocess.run(
['pylint', project_dir, '--output-format=json'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False # Don't raise exception on non-zero exit
)
if result.stderr:
print("Pylint encountered an error:")
print(result.stderr)
# Continue processing even if pylint reports errors (like syntax errors)
# Parse JSON output
pylint_output = json.loads(result.stdout)
return pylint_output
except FileNotFoundError:
print("Pylint is not installed or not found in the system PATH.")
return None
except json.JSONDecodeError:
print("Failed to parse pylint output. Ensure pylint is producing valid JSON.")
return None
def extract_errors(pylint_output):
"""
Extracts only error and fatal issues from pylint output.
Args:
pylint_output (list): The JSON-parsed output from pylint.
Returns:
list: Filtered list of error issues.
"""
error_issues = [
{
'File': issue.get('path', ''),
'Line': issue.get('line', ''),
'Column': issue.get('column', ''),
'Symbol': issue.get('symbol', ''),
'Message': issue.get('message', ''),
'Type': issue.get('type', '')
}
for issue in pylint_output
if issue.get('type', '').lower() in ['error', 'fatal'] and issue.get('message-id', '').startswith(('E', 'F'))
]
return error_issues
def main():
# Define your project directory
project_dir = Path(r'C:\Users\PC\Desktop\Leo-Major\Memoraith')
if not project_dir.exists():
print(f"The directory {project_dir} does not exist.")
return
print(f"Running pylint on {project_dir}...")
pylint_output = run_pylint(str(project_dir))
if pylint_output is None:
print("No pylint output to process.")
return
relevant_errors = extract_errors(pylint_output)
print("\n=== Pylint Errors ===")
if relevant_errors:
for issue in relevant_errors:
print(f"{issue['File']}:{issue['Line']}:{issue['Column']} - {issue['Message']} [{issue['Symbol']}] ({issue['Type'].capitalize()})")
else:
print("No errors found.")
# Optionally, save the results to a file
save_results = True # Set to False if you don't want to save
if save_results:
errors_file = project_dir / 'pylint_errors.txt'
with open(errors_file, 'w', encoding='utf-8') as f:
for issue in relevant_errors:
f.write(f"{issue['File']}:{issue['Line']}:{issue['Column']} - {issue['Message']} [{issue['Symbol']}] ({issue['Type'].capitalize()})\n")
print(f"\nErrors saved to {errors_file}")
if __name__ == "__main__":
main()
--------------------------------------------------------------------------------
File: C:\Users\PC\Desktop\Leo-Major\Memoraith\setup.py
from setuptools import setup, find_packages
setup(
name="memoraith",
version="0.3.5",
author="Mehdi El Jouhfi",
author_email="midojouhfi@gmail.com",
description="Advanced lightweight model profiler for deep learning frameworks",
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
url="https://github.com/mehdi342/Memoraith",
packages=find_packages(exclude=['tests', 'tests.*']),
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
python_requires='>=3.7',
install_requires=[
'torch>=1.7.0',
'tensorflow>=2.4.0',
'matplotlib>=3.3.0',
'seaborn>=0.11.0',
'plotly>=4.14.0',
'pandas>=1.2.0',
'jinja2>=2.11.0',
'pdfkit>=0.6.0',
'psutil>=5.8.0',
'pynvml>=8.0.0',
'colorama>=0.4.4',
'tqdm>=4.60.0',
'aiofiles>=0.6.0',
'asyncio>=3.4.3',
'networkx>=2.5',
],
extras_require={
'full': [
'torch>=1.7.0',
'tensorflow>=2.4.0',
'tensorboard>=2.4.0',
'optuna>=2.3.0',
'ray>=1.2.0',
],
'dev': [
'pytest>=6.2.0',
'pytest-asyncio>=0.14.0',
'black>=20.8b1',
'isort>=5.7.0',
'flake8>=3.8.0',
'mypy>=0.800',
'tox>=3.20.0',
'sphinx>=3.4.3',
'sphinx-rtd-theme>=0.5.1',
],
},
entry_points={
'console_scripts': [
'memoraith=memoraith.cli:main',
],
},
include_package_data=True,
zip_safe=False,
project_urls={
'Bug Reports': 'https://github.com/mehdi342/Memoraith/issues',
'Source': 'https://github.com/mehdi342/Memoraith/',
},
)
--------------------------------------------------------------------------------
File: C:\Users\PC\Desktop\Leo-Major\Memoraith\testdata.py
import os
import re
def generate_project_structure(directory, indent_level=0):
structure = ""
for root, dirs, files in os.walk(directory):
if 'venv' in root:
continue
level = root.replace(directory, '').count(os.sep)
indent = '│ ' * (level - indent_level)
structure += f"{indent}├── {os.path.basename(root)}/\n"
sub_indent = '│ ' * (level + 1 - indent_level)
for file in files:
if file.endswith('.py'):
structure += f"{sub_indent}├── {file}\n"
dirs[:] = [d for d in dirs if d != 'venv'] # Skip venv directory
return structure
def extract_classes_and_methods(content):
class_regex = r'class\s+(\w+)\s*(\(.*?\))?:'
method_regex = r'def\s+(\w+)\s*\(.*?\):'
extracted_content = ""
class_matches = re.findall(class_regex, content)
for class_match in class_matches:
class_name = class_match[0]
extracted_content += f"\nClass: {class_name}\n"
extracted_content += "-" * 80 + "\n"
method_matches = re.findall(method_regex, content)
for method_match in method_matches:
extracted_content += f" Method: {method_match}\n"
return extracted_content
def read_files_recursively(directory):
content = ""
for root, dirs, files in os.walk(directory):
if 'venv' in root:
continue
for file in files:
if file.endswith('.py'):
file_path = os.path.join(root, file)
print(f"Processing file: {file_path}")
content += f"File: {file_path}\n\n"
try:
with open(file_path, 'r', encoding='utf-8') as f:
file_content = f.read()
content += file_content
extracted_classes_methods = extract_classes_and_methods(file_content)
content += extracted_classes_methods
except UnicodeDecodeError:
try:
with open(file_path, 'r', encoding='ISO-8859-1') as f:
file_content = f.read()
content += file_content
except Exception as e:
content += f"Error reading file: {e}"
content += "\n\n" + "-"*80 + "\n\n"
return content
def save_content_to_txt(directory, output_file):
print("Starting the process...")
project_structure = generate_project_structure(directory)
file_content = read_files_recursively(directory)
with open(output_file, 'w', encoding='utf-8') as f:
f.write("Project Structure:\n\n")
f.write(project_structure)
f.write("\n\n" + "="*80 + "\n\n")
f.write(file_content)
print("Process completed successfully.")
# Usage
project_directory = r"C:\Users\PC\Desktop\Leo-Major\Memoraith"
output_file = r"C:\Users\PC\Desktop\Leo-Major\Memoraith\projetoo_content.txt"
try:
save_content_to_txt(project_directory, output_file)
except PermissionError:
print("Permission denied. Please check your write permissions or choose a different output location.")
except Exception as e:
print(f"An error occurred: {e}")
--------------------------------------------------------------------------------
File: C:\Users\PC\Desktop\Leo-Major\Memoraith\examples\example_pytorch.py
# PyTorch example
--------------------------------------------------------------------------------
File: C:\Users\PC\Desktop\Leo-Major\Memoraith\examples\example_tensorflow.py
import tensorflow as tf
from memoraith import profile_model, set_output_path
def create_model():
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(10,)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(1)
])
return model
@profile_model(memory=True, computation=True, gpu=True)
def train_model(model, epochs=5):
model.compile(optimizer='adam', loss='mse')
# Generate some dummy data
x_train = tf.random.normal((1000, 10))
y_train = tf.random.normal((1000, 1))
model.fit(x_train, y_train, epochs=epochs, verbose=1)
if __name__ == "__main__":
set_output_path('tensorflow_profiling_results/')
model = create_model()
train_model(model)
--------------------------------------------------------------------------------
File: C:\Users\PC\Desktop\Leo-Major\Memoraith\memoraith\cli.py
import argparse
import asyncio
from typing import Any
from memoraith import profile_model, set_output_path
from memoraith.config import config
from memoraith.exceptions import MemoraithError
async def main() -> None:
parser = argparse.ArgumentParser(description="Memoraith: Lightweight Model Profiler")
parser.add_argument("module", help="Python module containing the model and training function")
parser.add_argument("function", help="Name of the function to profile")
parser.add_argument("--output", default="memoraith_reports", help="Output directory for profiling results")
parser.add_argument("--memory", action="store_true", help="Enable memory profiling")
parser.add_argument("--computation", action="store_true", help="Enable computation time profiling")
parser.add_argument("--gpu", action="store_true", help="Enable GPU profiling")
parser.add_argument("--real-time", action="store_true", help="Enable real-time visualization")
parser.add_argument("--config", help="Path to configuration file")
parser.add_argument("--report-format", choices=['html', 'pdf'], default='html', help="Report format")
args = parser.parse_args()
try:
if args.config:
config.load_from_file(args.config)
set_output_path(args.output)
module = __import__(args.module)
func = getattr(module, args.function)
@profile_model(memory=args.memory, computation=args.computation, gpu=args.gpu,
real_time_viz=args.real_time, report_format=args.report_format)
async def wrapped_func(*args: Any, **kwargs: Any) -> Any:
if asyncio.iscoroutinefunction(func):
return await func(*args, **kwargs)
else:
return await asyncio.to_thread(func, *args, **kwargs)
await wrapped_func()
except ImportError as e:
print(f"Error: Could not import module '{args.module}'. {str(e)}")
except AttributeError as e:
print(f"Error: Function '{args.function}' not found in module '{args.module}'. {str(e)}")
except MemoraithError as e:
print(f"Memoraith Error: {str(e)}")
except Exception as e:
print(f"An unexpected error occurred: {str(e)}")
if __name__ == "__main__":
asyncio.run(main())
--------------------------------------------------------------------------------
File: C:\Users\PC\Desktop\Leo-Major\Memoraith\memoraith\config.py
import os
import logging
from pathlib import Path
from typing import Dict, Any, Optional
from dotenv import load_dotenv
import yaml
import json
import torch.optim as optim
import torch.nn as nn
class Config:
"""
Comprehensive configuration management for Memoraith.
Includes all existing functionality plus enhancements.
"""
def __init__(self):
self.output_path = Path('memoraith_reports/')
self.enable_gpu = False
self.enable_memory = True
self.enable_time = True
self.log_level = logging.INFO
self.report_format = 'html'
self.real_time_viz = False
self.profiling_interval = 0.1
self.max_memory_samples = 1000
self.bottleneck_threshold = 0.1
self.anomaly_threshold = 3.0
self.batch_size = 32
self.max_epochs = 100
self.learning_rate = 0.001
self.optimizer = 'adam'
self.loss_function = 'cross_entropy'
# Load environment variables
load_dotenv()
# Load config from environment variables
self.load_from_env()
def __getitem__(self, key: str) -> Any:
return getattr(self, key, None)
def __setitem__(self, key: str, value: Any) -> None:
setattr(self, key, value)
def set_output_path(self, path: str) -> None:
"""Set the output path for profiling reports."""
self.output_path = Path(path)
self.output_path.mkdir(parents=True, exist_ok=True)
def enable_gpu_profiling(self, enable: bool) -> None:
"""Enable or disable GPU profiling."""
self.enable_gpu = enable
def set_log_level(self, level: int) -> None:
"""Set the logging level."""
self.log_level = level
def set_batch_size(self, size: int) -> None:
"""Set the batch size for training."""
self.batch_size = size
def set_max_epochs(self, epochs: int) -> None:
"""Set the maximum number of epochs for training."""
self.max_epochs = epochs
def set_learning_rate(self, lr: float) -> None:
"""Set the learning rate for training."""
self.learning_rate = lr
def set_optimizer(self, optimizer: str) -> None:
"""Set the optimizer for training."""
self.optimizer = optimizer
def set_loss_function(self, loss: str) -> None:
"""Set the loss function for training."""
self.loss_function = loss
def load_from_env(self) -> None:
"""Load configuration from environment variables."""
self.output_path = Path(os.getenv('MEMORAITH_OUTPUT_PATH', str(self.output_path)))
self.enable_gpu = os.getenv('MEMORAITH_ENABLE_GPU', str(self.enable_gpu)).lower() == 'true'
self.enable_memory = os.getenv('MEMORAITH_ENABLE_MEMORY', str(self.enable_memory)).lower() == 'true'
self.enable_time = os.getenv('MEMORAITH_ENABLE_TIME', str(self.enable_time)).lower() == 'true'
self.log_level = getattr(logging, os.getenv('MEMORAITH_LOG_LEVEL', 'INFO'))
self.batch_size = int(os.getenv('MEMORAITH_BATCH_SIZE', str(self.batch_size)))
self.max_epochs = int(os.getenv('MEMORAITH_MAX_EPOCHS', str(self.max_epochs)))
self.learning_rate = float(os.getenv('MEMORAITH_LEARNING_RATE', str(self.learning_rate)))
self.optimizer = os.getenv('MEMORAITH_OPTIMIZER', self.optimizer)
self.loss_function = os.getenv('MEMORAITH_LOSS_FUNCTION', self.loss_function)
def load_from_file(self, config_file: str) -> None:
"""Load configuration from a YAML file."""
with open(config_file, 'r') as f:
config_data = yaml.safe_load(f)
for key, value in config_data.items():
if hasattr(self, key):
setattr(self, key, value)
# Update main attributes if they're in the loaded config
if 'output_path' in config_data:
self.set_output_path(config_data['output_path'])
if 'enable_gpu' in config_data:
self.enable_gpu_profiling(config_data['enable_gpu'])
if 'log_level' in config_data:
self.set_log_level(getattr(logging, config_data['log_level']))
if 'batch_size' in config_data:
self.set_batch_size(config_data['batch_size'])
if 'max_epochs' in config_data:
self.set_max_epochs(config_data['max_epochs'])
if 'learning_rate' in config_data:
self.set_learning_rate(config_data['learning_rate'])
if 'optimizer' in config_data:
self.set_optimizer(config_data['optimizer'])
if 'loss_function' in config_data:
self.set_loss_function(config_data['loss_function'])
def to_dict(self) -> Dict[str, Any]:
"""Convert configuration to a dictionary."""
return {k: v for k, v in self.__dict__.items() if not k.startswith('_')}
def get_optimizer(self, parameters: Any) -> Optional[Any]:
"""Get the optimizer instance based on the configuration."""
optimizer_map = {
'adam': optim.Adam,
'sgd': optim.SGD,
'rmsprop': optim.RMSprop,
# Add more optimizers as needed
}
optimizer_class = optimizer_map.get(self.optimizer.lower())
if optimizer_class:
return optimizer_class(parameters, lr=self.learning_rate)
else:
logging.error(f"Optimizer '{self.optimizer}' not supported.")
return None
def get_loss_function(self) -> Optional[Any]:
"""Get the loss function based on the configuration."""
loss_map = {
'cross_entropy': nn.CrossEntropyLoss,
'mse': nn.MSELoss,
'bce': nn.BCELoss,
# Add more loss functions as needed
}
loss_class = loss_map.get(self.loss_function.lower())
if loss_class:
return loss_class()
else:
logging.error(f"Loss function '{self.loss_function}' not supported.")
return None
def save_to_file(self, filename: str) -> None:
"""Save the current configuration to a JSON file."""
with open(filename, 'w') as f:
json.dump(self.to_dict(), f, indent=2)
logging.info(f"Configuration saved to {filename}")
def validate(self) -> bool:
"""Validate the current configuration."""
# Add validation logic here
valid = True
if not isinstance(self.output_path, Path):
logging.error("output_path must be a Path object")
valid = False
if not isinstance(self.enable_gpu, bool):
logging.error("enable_gpu must be a boolean")
valid = False
# Add more validation checks as needed
return valid
def set_profiling_interval(self, interval: float) -> None:
"""Set the profiling interval."""
self.profiling_interval = interval
def set_max_memory_samples(self, samples: int) -> None:
"""Set the maximum number of memory samples to collect."""
self.max_memory_samples = samples
def set_bottleneck_threshold(self, threshold: float) -> None:
"""Set the threshold for detecting bottlenecks."""
self.bottleneck_threshold = threshold
def set_anomaly_threshold(self, threshold: float) -> None:
"""Set the threshold for detecting anomalies."""
self.anomaly_threshold = threshold
def enable_real_time_visualization(self, enable: bool) -> None:
"""Enable or disable real-time visualization."""
self.real_time_viz = enable
def set_report_format(self, format: str) -> None:
"""Set the report format (html or pdf)."""
if format.lower() in ['html', 'pdf']:
self.report_format = format.lower()
else:
logging.error(f"Unsupported report format: {format}. Using default (html).")
def get_full_config(self) -> Dict[str, Any]:
"""Get the full configuration as a dictionary."""
return self.to_dict()
def reset_to_defaults(self) -> None:
"""Reset all configuration options to their default values."""
self.__init__()
def __str__(self) -> str:
"""String representation of the Config object."""
return f"Config(output_path={self.output_path}, enable_gpu={self.enable_gpu}, ...)"
def __repr__(self) -> str:
"""Detailed string representation of the Config object."""
return self.__str__()
# Global configuration instance
config = Config()
import os
import logging
from pathlib import Path
from typing import Dict, Any, Optional
from dotenv import load_dotenv
import yaml
import json
import torch.optim as optim
import torch.nn as nn
class Config:
"""
Comprehensive configuration management for Memoraith.
Includes all existing functionality plus enhancements.
"""
def __init__(self):
self.output_path = Path('memoraith_reports/')
self.enable_gpu = False
self.enable_memory = True
self.enable_time = True
self.log_level = logging.INFO
self.report_format = 'html'
self.real_time_viz = False
self.profiling_interval = 0.1
self.max_memory_samples = 1000
self.bottleneck_threshold = 0.1
self.anomaly_threshold = 3.0
self.batch_size = 32
self.max_epochs = 100
self.learning_rate = 0.001
self.optimizer = 'adam'
self.loss_function = 'cross_entropy'
# Load environment variables
load_dotenv()
# Load config from environment variables
self.load_from_env()
def __getitem__(self, key: str) -> Any:
return getattr(self, key, None)
def __setitem__(self, key: str, value: Any) -> None:
setattr(self, key, value)
def set_output_path(self, path: str) -> None:
"""Set the output path for profiling reports."""
self.output_path = Path(path)
self.output_path.mkdir(parents=True, exist_ok=True)
def enable_gpu_profiling(self, enable: bool) -> None:
"""Enable or disable GPU profiling."""
self.enable_gpu = enable
def set_log_level(self, level: str) -> None:
"""Set the logging level."""
self.log_level = level
def set_batch_size(self, size: int) -> None:
"""Set the batch size for training."""
self.batch_size = size
def set_max_epochs(self, epochs: int) -> None:
"""Set the maximum number of epochs for training."""
self.max_epochs = epochs
def set_learning_rate(self, lr: float) -> None:
"""Set the learning rate for training."""
self.learning_rate = lr
def set_optimizer(self, optimizer: str) -> None:
"""Set the optimizer for training."""
self.optimizer = optimizer
def set_loss_function(self, loss: str) -> None:
"""Set the loss function for training."""
self.loss_function = loss
def load_from_env(self) -> None:
"""Load configuration from environment variables."""
self.output_path = Path(os.getenv('MEMORAITH_OUTPUT_PATH', str(self.output_path)))
self.enable_gpu = os.getenv('MEMORAITH_ENABLE_GPU', str(self.enable_gpu)).lower() == 'true'
self.enable_memory = os.getenv('MEMORAITH_ENABLE_MEMORY', str(self.enable_memory)).lower() == 'true'
self.enable_time = os.getenv('MEMORAITH_ENABLE_TIME', str(self.enable_time)).lower() == 'true'
self.log_level = os.getenv('MEMORAITH_LOG_LEVEL', 'INFO')
self.batch_size = int(os.getenv('MEMORAITH_BATCH_SIZE', str(self.batch_size)))
self.max_epochs = int(os.getenv('MEMORAITH_MAX_EPOCHS', str(self.max_epochs)))
self.learning_rate = float(os.getenv('MEMORAITH_LEARNING_RATE', str(self.learning_rate)))
self.optimizer = os.getenv('MEMORAITH_OPTIMIZER', self.optimizer)
self.loss_function = os.getenv('MEMORAITH_LOSS_FUNCTION', self.loss_function)
def load_from_file(self, config_file: str) -> None:
"""Load configuration from a YAML file."""
with open(config_file, 'r') as f:
config_data = yaml.safe_load(f)
for key, value in config_data.items():
if hasattr(self, key):
setattr(self, key, value)
# Update main attributes if they're in the loaded config
if 'output_path' in config_data:
self.set_output_path(config_data['output_path'])
if 'enable_gpu' in config_data:
self.enable_gpu_profiling(config_data['enable_gpu'])
if 'log_level' in config_data:
self.log_level = config_data['log_level']
if 'batch_size' in config_data:
self.set_batch_size(config_data['batch_size'])
if 'max_epochs' in config_data:
self.set_max_epochs(config_data['max_epochs'])
if 'learning_rate' in config_data:
self.set_learning_rate(config_data['learning_rate'])
if 'optimizer' in config_data:
self.set_optimizer(config_data['optimizer'])
if 'loss_function' in config_data:
self.set_loss_function(config_data['loss_function'])
def to_dict(self) -> Dict[str, Any]:
"""Convert configuration to a dictionary."""
return {k: v for k, v in self.__dict__.items() if not k.startswith('_')}
def get_optimizer(self, parameters: Any) -> Optional[Any]:
"""Get the optimizer instance based on the configuration."""
optimizer_map = {
'adam': optim.Adam,
'sgd': optim.SGD,
'rmsprop': optim.RMSprop,
# Add more optimizers as needed
}
optimizer_class = optimizer_map.get(self.optimizer.lower())
if optimizer_class:
return optimizer_class(parameters, lr=self.learning_rate)
else:
logging.error(f"Optimizer '{self.optimizer}' not supported.")
return None
def get_loss_function(self) -> Optional[Any]:
"""Get the loss function based on the configuration."""
loss_map = {
'cross_entropy': nn.CrossEntropyLoss,
'mse': nn.MSELoss,
'bce': nn.BCELoss,
# Add more loss functions as needed
}
loss_class = loss_map.get(self.loss_function.lower())
if loss_class:
return loss_class()
else:
logging.error(f"Loss function '{self.loss_function}' not supported.")
return None
def save_to_file(self, filename: str) -> None:
"""Save the current configuration to a JSON file."""
with open(filename, 'w') as f:
json.dump(self.to_dict(), f, indent=2)
logging.info(f"Configuration saved to {filename}")
def validate(self) -> bool:
"""Validate the current configuration."""
# Add validation logic here
valid = True
if not isinstance(self.output_path, Path):
logging.error("output_path must be a Path object")
valid = False
if not isinstance(self.enable_gpu, bool):
logging.error("enable_gpu must be a boolean")
valid = False
# Add more validation checks as needed
return valid
def set_profiling_interval(self, interval: float) -> None:
"""Set the profiling interval."""
self.profiling_interval = interval
def set_max_memory_samples(self, samples: int) -> None:
"""Set the maximum number of memory samples to collect."""
self.max_memory_samples = samples
def set_bottleneck_threshold(self, threshold: float) -> None:
"""Set the threshold for detecting bottlenecks."""
self.bottleneck_threshold = threshold
def set_anomaly_threshold(self, threshold: float) -> None:
"""Set the threshold for detecting anomalies."""
self.anomaly_threshold = threshold
def enable_real_time_visualization(self, enable: bool) -> None:
"""Enable or disable real-time visualization."""
self.real_time_viz = enable
def set_report_format(self, format: str) -> None:
"""Set the report format (html or pdf)."""
if format.lower() in ['html', 'pdf']:
self.report_format = format.lower()
else:
logging.error(f"Unsupported report format: {format}. Using default (html).")
def get_full_config(self) -> Dict[str, Any]:
"""Get the full configuration as a dictionary."""
return self.to_dict()
def reset_to_defaults(self) -> None:
"""Reset all configuration options to their default values."""
self.__init__()
def __str__(self) -> str:
"""String representation of the Config object."""
return f"Config(output_path={self.output_path}, enable_gpu={self.enable_gpu}, ...)"
def __repr__(self) -> str:
"""Detailed string representation of the Config object."""
return self.__str__()
# Global configuration instance
config = Config()
Class: Config
--------------------------------------------------------------------------------
Method: __init__
Method: __init__
Class: Config
--------------------------------------------------------------------------------
Method: __init__
Method: __init__
--------------------------------------------------------------------------------
File: C:\Users\PC\Desktop\Leo-Major\Memoraith\memoraith\exceptions.py
class MemoraithError(Exception):
"""Base exception class for Memoraith."""
def __init__(self, message: str):
self.message = message