Skip to content

Commit

Permalink
Add an option to disable default compilation (#1787)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattdangerw authored Aug 21, 2024
1 parent 5299cd4 commit 931ac28
Show file tree
Hide file tree
Showing 5 changed files with 13 additions and 7 deletions.
2 changes: 0 additions & 2 deletions keras_nlp/src/models/causal_lm.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,6 @@ class CausalLM(Task):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Default compilation.
self.compile()

def compile(
self,
Expand Down
2 changes: 0 additions & 2 deletions keras_nlp/src/models/classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,6 @@ class Classifier(Task):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Default compilation.
self.compile()

def compile(
self,
Expand Down
2 changes: 0 additions & 2 deletions keras_nlp/src/models/masked_lm.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ class MaskedLM(Task):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Default compilation.
self.compile()

def compile(
self,
Expand Down
10 changes: 9 additions & 1 deletion keras_nlp/src/models/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,27 @@ class Task(PipelineModel):
to load a pre-trained config and weights. Calling `from_preset()` on a task
will automatically instantiate a `keras_nlp.models.Backbone` and
`keras_nlp.models.Preprocessor`.
Args:
compile: boolean, defaults to `True`. If `True` will compile the model
with default parameters on construction. Model can still be
recompiled with a new loss, optimizer and metrics before training.
"""

backbone_cls = None
preprocessor_cls = None

def __init__(self, *args, **kwargs):
def __init__(self, *args, compile=True, **kwargs):
super().__init__(*args, **kwargs)
self._functional_layer_ids = set(
id(layer) for layer in self._flatten_layers()
)
self._initialized = True
if self.backbone is not None:
self.dtype_policy = self._backbone.dtype_policy
if compile:
# Default compilation.
self.compile()

def preprocess_samples(self, x, y=None, sample_weight=None):
if self.preprocessor is not None:
Expand Down
4 changes: 4 additions & 0 deletions keras_nlp/src/tests/test_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,10 @@ def run_task_test(
task.preprocessor = None
task.fit(ds.map(preprocessor))
task.preprocessor = preprocessor
# Turn off default compilation, should error during `fit()`.
task = cls(**init_kwargs, compile=False)
with self.assertRaisesRegex(ValueError, "You must call `compile"):
task.fit(ds)

def run_preset_test(
self,
Expand Down

0 comments on commit 931ac28

Please sign in to comment.