MEMBER src/crane/main.py SHA256 a4e2a90a311d9fd80250c721665bc88738cd133f93f5ed10d023b8406046824c
924:                             raise e
925:                         print(f"Exception while parsing:\n {e}")
926:                         continue  # Skip altering the scores for this batch
927:                 
928:                 self.structured_gen = next_gen # Update the current generation
929:             else:
930:                 #self.tokenizer.decode(next_session_tokens[0, :self.last_constrained_end + 1])
931:                 unconstrained_gen = self.tokenizer.decode(next_session_tokens[0, self.last_constrained_end + 1:], skip_special_tokens=True)
932:                 if self.start_symbol in unconstrained_gen:
933:                     self.current_state = ConstrainedMode
934:                     self._trace = Trace()
935:                     self.start_constrained_from = len(next_session_tokens[0])
936:                     self.structured_offset = [len(self.overall_gen[i]) + 1 for i in range(self.num_outputs)]
937:                     if self.start_in_grammar:
938:                         self.structured_gen = [self.start_symbol for _ in range(self.num_outputs)]
939:                         self._trace.add_token(-2, len(self.session_tokens[0]), self.start_symbol, 0, len(self.start_symbol))
940:                         # import pdb; pdb.set_trace()
941:                     else:
942:                         self.structured_gen = ['' for _ in range(self.num_outputs)]
943:                     for idx, ip in enumerate(self.inc_parsers):
944:                         ip.reset()
945:                     parse_results = [ip.get_acceptable_next_terminals(self.structured_gen[idx]) for idx, ip in enumerate(self.inc_parsers)]
946:                 
947:             
948:             # Update the current generation
949:             self.session_tokens = next_session_tokens
950:             self.overall_gen = self.tokenizer.batch_decode(self.session_tokens[:, self.start_from:], skip_special_tokens=True)
951:             
952: 
953:             # Update attention mask
954:             self.model_kwargs['attention_mask'] = torch.cat([self.model_kwargs['attention_mask'], torch.ones((self.model_kwargs['attention_mask'].size(0), 1), dtype=self.model_kwargs['attention_mask'].dtype).to(self.device)], dim=-1)
988:             this_peer_finished = unfinished_sequences.max() == 0     
989: 
990:         # Update the model kwargs at the end of the generation 
991:         # self._post_update_model_kwargs(**self.model_kwargs)
992: 
993:         output = [gen[:self.cursors[idx]] for idx, gen in enumerate(self.overall_gen)]
994:         return output
995: 
996:     def _get_next_token_grammar(
997:             self, 
998:             gen_mode: GenerationMode, 
999:             next_token_scores: torch.FloatTensor,
1000:             parse_results: ParseResult
1001:             ) -> Tuple[torch.LongTensor, torch.Tensor]:
1002:         """
1003:         Calling grammar decoder is expensive. Hence, in the opportunist mode, we call it only when
1004:         the standard generation is syntactically incorrect
1005:         """
1006:         
1007:         next_token, next_token_probs = self._get_next_token(gen_mode, self.session_tokens, self.logit_warper, next_token_scores)
1008:         
1009:         # if '+-' in self.tokenizer.decode(torch.cat((self.session_tokens[0], next_token[0].unsqueeze(0)), dim=-1)):
1010:         #     import pdb; pdb.set_trace()
1011: 
1012:         if self.current_state == UnconstrainedMode:
1013:             return next_token, next_token_probs
1014:         
1015:         # if '(' in self.tokenizer.decode(next_token[0]):
1016:         #     import pdb; pdb.set_trace()
1017:         
1018:         # For the cases when the grammar is violated, we apply the mask
1019:         
1020:         invalid_at_least_onnce = False
1021:         for idx in range(self.num_outputs):
1022:             is_valid, next_tok_idx = self._is_valid(idx, self.session_tokens[idx][self.start_constrained_from:], next_token[idx])
1023:             # if not is_valid:
1024:             #     import pdb; pdb.set_trace()
1025:             
1026:             next_token[idx] = next_tok_idx
MEMBER src/prompting/fol.py SHA256 be4607a7e81ede42a2b66a859f676dc5dd551facfa33533afa799e621ba0d4e4
25:         return completion
26: 
27:     def _parse_single_completion(self, input_ex, completion, parse_info):
28:         if 'Predicates:' in completion:
29:             completion = 'Predicates:' + completion.split('Predicates:')[1]
30:         logic_program = completion.split('------')[0]
31:         
32:         print(f"\nLogic Program:\n {logic_program}\n\n")
33:         logic_program = self._replace_symbols(logic_program)
34:         logic_program = logic_program.split('Note')[0]
35:         logic_program = logic_program.strip()
36:         print(f"\nLogic Program after symbol replacement:\n {logic_program}\n\n")
37: 
38:         answer = None
39:         compiles = False
40:         rand_ans = False
41:         error_message = None
42: 
43:         try:
44:             self.fol_parser.parse(logic_program)
45:             is_parsed = True
46:         except:
47:             is_parsed = False
48: 
49:         try:
50:             # import pdb; pdb.set_trace()
51:             program = fol_eval.FOL_Prover9_Program(logic_program)
52:             if program.compiles:
53:                 compiles = True
54:             else:
55:                 raise Exception("Failed to compile logic program")
56:             answer, error_message = program.execute_program()
57:             answer = program.answer_mapping(answer)
58:         
59:         except Exception as e:
60:             print(e)
61:             error_message = str(e)
62: 
63:         if answer is None:
64:             print("\n\nRandomly choosing answer\n\n")
65:             answer = random.choice(['A', 'B', 'C'])
66:             rand_ans = True
67: 
68:         map_label_to_answer = {'True': 'A', 'False': 'B', 'Uncertain': 'C'}
69:         ground_truth = map_label_to_answer[input_ex['answer']]
70: 
71:         print(f"rand_ans: {rand_ans}, answer: {answer}, ground_truth: {ground_truth}")
72:         print(f"FINAL ANSWER: {(not rand_ans) and (answer == ground_truth)}")
73: 
74:         return dict(
75:             idx=input_ex['idx'],
76:             correct=((not rand_ans) and (answer == ground_truth)),
77:             llm_completion = input_ex['llm_response'], 
78:             compiles=compiles,
79:             is_parsed=is_parsed,
80:             random=(rand_ans),
81:             logic_program=logic_program,
82:             answer=answer,  
83:             ground_truth=ground_truth,
84:             error_message=error_message,
85:             total_time = input_ex['response_info']['time'] + parse_info['time'],
ARXIV LANDING METADATA
<meta property="og:url" content="https://arxiv.org/abs/2502.09061v4" />
  [Submitted on 13 Feb 2025 (<a href="https://arxiv.org/abs/2502.09061v1">v1</a>), last revised 5 Sep 2025 (this version, v4)]</div>
    <a class="mobile-submission-download" href="https://arxiv.org/html/2502.09061v4">HTML (experimental)</a>
          <td class="tablecell comments mathjax">Accepted at ICML 2025, Code at: <a href="https://github.com/uiuc-focal-lab/CRANE" rel="external noopener nofollow" class="link-external link-https">this https URL</a></td>
              <a href="https://arxiv.org/abs/2502.09061v4">arXiv:2502.09061v4</a> [cs.PL]</span> for this version)
      <h2>Submission history</h2> From: Debangshu Banerjee [<a href="/show-email/12e8af28/2502.09061" rel="nofollow">view email</a>]      <br/>            <strong><a href="/abs/2502.09061v1" rel="nofollow">[v1]</a></strong>
    <strong>[v4]</strong>
View a PDF of the paper titled CRANE: Reasoning with constrained LLM generation, by Debangshu Banerjee and 4 other authors</div><li><a href="/pdf/2502.09061" aria-describedby="download-button-info" accesskey="f" class="abs-button download-pdf">View PDF</a></li><li><a href="https://arxiv.org/html/2502.09061v4" class="abs-button" id="latexml-download-link">HTML (experimental)</a></li><li><a href="/src/2502.09061" class="abs-button download-eprint">TeX Source