Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix prefix space issues with certain tokenizers #156

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions catwalk/models/language_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,8 +368,10 @@ def _make_model(
**kwargs)

@staticmethod
def _prefix_with_space(s: str) -> str:
if not s.startswith(' '):
def _prefix_with_space(s: str, needed=True) -> str:
if not needed and s.startswith(' '):
return s[1:]
elif not s.startswith(' ') and needed:
return f" {s}"
else:
return s
Expand All @@ -384,8 +386,14 @@ def _run_loglikelihood(
model_max_length: Optional[int] = None
) -> Sequence[Dict]:

prefix_space_needed = True
# Hack to detect tokenizer which treats words at start of sentences as having a prefix space,
# e.g., Llama tokenizers
if tokenizer.tokenize("A")[0] == tokenizer.tokenize(" A")[-1]:
prefix_space_needed = False
tokenized_contexts = tokenizer([t[0] for t in tuples], add_special_tokens=False)
tokenized_continuations = tokenizer([self._prefix_with_space(t[1]) for t in tuples], add_special_tokens=False)
tokenized_continuations = tokenizer([self._prefix_with_space(t[1], prefix_space_needed) for t in tuples],
add_special_tokens=False)

# We don't need token_type_ids, and it trips up some models apparently (like LLaMA)
if 'token_type_ids' in tokenized_contexts:
Expand Down