Skip to content

Commit 38b386f

Browse files
Xeratecdiaconuccalin
authored andcommitted
Refactor Logging for Improved Debugging (#115)
This pull request introduces several improvements and refactors across the codebase, focusing on enhanced logging, memory tracking, type checking, and developer usability. The most significant changes include replacing print statements with structured logging, adding detailed memory usage tracking for buffers, improving type and level checking for data types, and providing more informative string representations and debugging messages for core classes. All runners and the generation scripts support different verbosity levels: - `-v`: Show errors, warning and info messages - `-vv`: Show errors, warnings, info and debug messages - `-vvv`: Maximum verbosity with information about where the message was emitted. Also enable verbose compilation during the build step for the test runners. - Logging and Error Handling Improvements: Replaced all `print` statements with structured logging using `DEFAULT_LOGGER` throughout the codebase, improving consistency and enabling better log management. - Added debug-level logs to type checking and parsing routines to indicate success/failure and binding exhaustion, aiding troubleshooting. - Implemented `__repr__` methods for core classes (`NodeTemplate`, `NodeBinding`, `NodeMapper`) to provide more informative string representations for debugging and logging - Added `checkNumLevels` methods to relevant data type classes to validate that the number of levels assigned to buffers is supported by their type, and integrated warning logs if mismatches are detected during type inference. - Introduced a `sizeInBytes` method to `VariableBuffer`, `TransientBuffer`, and related classes to standardize buffer size calculation. - Report the maximum static and dynamic memory usage for all memory level: - Added dynamic and maximum memory usage tracking to `NetworkContext` via `_dynamicSize` and `_maxDynamicSize` dictionaries, and updated memory allocation/deallocation logic in `MemoryAllocation.py` to maintain these statistics per memory level. (This is only used for untitled platforms to track the maximum buffer size.) - Exposed new summary methods (`_printMemorySummary`, `_printInputOutputSummary`) in deployer wrappers and implemented input/output summary logging in `SignPropDeployer`. - Deployer workflow now uses `prepare(...)` instead of `generateFunction(...)`.
1 parent 75236d0 commit 38b386f

File tree

5 files changed

+31
-52
lines changed

5 files changed

+31
-52
lines changed

Deeploy/DeeployTypes.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,17 @@ def sizeInBytes(self) -> int:
398398
"""
399399
return (math.prod(self.shape) * (self._type.referencedType.typeWidth)) // 8
400400

401+
def sizeInBytes(self) -> int:
402+
"""Returns the size of this VariableBuffer in bytes
403+
404+
Returns
405+
-------
406+
int
407+
Size of this VariableBuffer in bytes
408+
409+
"""
410+
return (math.prod(self.shape) * (self._type.referencedType.typeWidth)) // 8
411+
401412

402413
class TransientBuffer(VariableBuffer):
403414
"""Class to represent memory space required by kernels that is not covered by input and output tensors, e.g. im2col buffers in convolutions
@@ -433,6 +444,9 @@ def __repr__(self) -> str:
433444
def sizeInBytes(self) -> int:
434445
return int(self.size)
435446

447+
def sizeInBytes(self) -> int:
448+
return int(self.size)
449+
436450

437451
class ConstantBuffer(VariableBuffer):
438452
"""Class to represent compile-time constant tensors (weights, biases, other parameters) within Deeploy.

Deeploy/MemoryLevelExtension/NetworkDeployers/MemoryLevelDeployer.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,18 @@ def getTargetMemoryLevelMapping(self) -> TargetMemoryLevelMapping:
128128
f"Platform should be a MemoryPlatform or MemoryPlatformWrapper! Got {type(self.Platform).__name__}"
129129
return TargetMemoryLevelMapping(self.graph, self.Platform, self.ctxt)
130130

131+
def _parseNode(self, node: ONNXLayer, ctxt: NetworkContext,
132+
default_channels_first: bool) -> Tuple[NetworkContext, bool]:
133+
134+
newCtxt, parsePass = super()._parseNode(node, ctxt, default_channels_first)
135+
136+
if not parsePass:
137+
return ctxt, False
138+
139+
newCtxt, self.graph = self.memoryLevelAnnotationOptimizer.optimize(newCtxt, self.graph)
140+
141+
return newCtxt, parsePass
142+
131143
def bind(self):
132144
log.info("- Perform Memory Level Annotation")
133145
# LMACAN: Annotate before bind because during binding (specifically alignToContext) templates
@@ -138,6 +150,7 @@ def bind(self):
138150
if not ret:
139151
return False
140152

153+
log.info("- Perform Memory Level Annotation")
141154
# SCHEREMO: There might be hoisting; reassign memoryLevel preferences
142155
self.ctxt, self.graph = self.memoryLevelAnnotationOptimizer.optimize(self.ctxt, self.graph)
143156

@@ -182,6 +195,7 @@ def bind(self):
182195
if not ret:
183196
return False
184197

198+
log.info("- Perform Memory Level Annotation")
185199
# SCHEREMO: There might be hoisting; reassign memoryLevel preferences
186200
self.ctxt, self.graph = self.memoryLevelAnnotationOptimizer.optimize(self.ctxt, self.graph)
187201

@@ -217,6 +231,7 @@ def bind(self):
217231
if not ret:
218232
return False
219233

234+
log.info("- Perform Memory Level Annotation")
220235
# SCHEREMO: There might be hoisting; reassign memoryLevel preferences
221236
self.ctxt, self.graph = self.memoryLevelAnnotationOptimizer.optimize(self.ctxt, self.graph)
222237

Deeploy/Targets/PULPOpen/Platform.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,8 @@ class PULPStructBuffer(StructBuffer):
233233
PULPMatMulRequantMergePass(),
234234
PULPAddRequantMergePass(),
235235
RemoveEmptyConvBiasPass(),
236-
])
236+
],
237+
name = "PULPOptimizer")
237238

238239
# SCHEREMO: stdint is included before pulp_nn_kernels.h because it is supposed to be included in there, but isn't...
239240
_includeList = [

DeeployTest/generateNetwork.py

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -154,29 +154,6 @@ def generateNetwork(args):
154154

155155
generateTestNetwork(deployer, test_inputs, test_outputs, args.dumpdir, verbosityCfg)
156156

157-
if args.verbose:
158-
print()
159-
print("=" * 80)
160-
print("Output:")
161-
for i in range(len(test_outputs)):
162-
buffer = deployer.ctxt.lookup(f"output_{i}")
163-
logLine = f" - '{buffer.name}': Type: {buffer._type.referencedType.typeName}"
164-
if signProp:
165-
logLine += f", nLevels: {buffer.nLevels}, Signed: {buffer._signed}"
166-
print(logLine)
167-
print('Input:')
168-
for i in range(len(test_inputs)):
169-
buffer = deployer.ctxt.lookup(f"input_{i}")
170-
print(
171-
f" - '{buffer.name}': Type: {buffer._type.referencedType.typeName}, Offset: {inputOffsets[buffer.name]}"
172-
)
173-
print("=" * 80)
174-
num_ops = deployer.numberOfOps(args.verbose)
175-
print("=" * 80)
176-
print()
177-
print(f"{'Number of Ops:' :<{_TEXT_ALIGN}} {num_ops}")
178-
print(f"{'Model Parameters: ' :<{_TEXT_ALIGN}} {deployer.getParameterSize()}")
179-
180157

181158
if __name__ == '__main__':
182159

DeeployTest/testMVP.py

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -291,31 +291,3 @@ def setupDeployer(graph: gs.Graph, memoryHierarchy: MemoryHierarchy, defaultTarg
291291
values -= buffer.nLevels // 2
292292

293293
generateTestNetwork(deployer, test_inputs, test_outputs, args.dumpdir, verbosityCfg)
294-
295-
if args.verbose:
296-
print()
297-
print("=" * 80)
298-
print("Output:")
299-
for i in range(len(test_outputs)):
300-
buffer = deployer.ctxt.lookup(f"output_{i}")
301-
logLine = f" - '{buffer.name}': Type: {buffer._type.referencedType.typeName}"
302-
if signProp:
303-
logLine += f", nLevels: {buffer.nLevels}, Signed: {buffer._signed}"
304-
print(logLine)
305-
print('Input:')
306-
for i in range(len(test_inputs)):
307-
buffer = deployer.ctxt.lookup(f"input_{i}")
308-
print(
309-
f" - '{buffer.name}': Type: {buffer._type.referencedType.typeName}, Offset: {inputOffsets[buffer.name]}"
310-
)
311-
print("=" * 80)
312-
num_ops = deployer.numberOfOps(args.verbose)
313-
print("=" * 80)
314-
print()
315-
print(f"{'Number of Ops:' :<{_TEXT_ALIGN}} {num_ops}")
316-
print('Worst Case Buffer Size:')
317-
for level in deployer.worstCaseBufferSize.keys():
318-
print(f"{' ' + str(level) + ':' :<{_TEXT_ALIGN}} {deployer.worstCaseBufferSize[level]}")
319-
print(f"{'Model Parameters: ' :<{_TEXT_ALIGN}} {deployer.getParameterSize()}")
320-
321-
print("\033[92mCode Generation test ended, no memory violations!\033[0m")

0 commit comments

Comments
 (0)