Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files129 unmodified lines1301311321331341351364 unmodified lines14114214314414514614714814915015115215315415515615715815915 unmodified lines17517617717817918018118218336 unmodified lines2202212222232242252262272282292302312322337 unmodified lines24124224324424524624724824925025125225325425516 unmodified lines27227327427527627727810 unmodified lines2892902912922932941 unmodified line29629729829930030130213 unmodified lines31631731831932032132213 unmodified lines33633733833934034110 unmodified lines3523533543553563573583593603613623633643652 unmodified lines36836937037137237313 unmodified lines3873883893903913923936 unmodified lines40040140240340440540625 unmodified lines43243343443543643728 unmodified lines466467468469470471472129 unmodified linesmargin-top: -5px;transform: rotate(315deg);}.box {border: 1px solid var(--body-text-color);padding: 5px;border-radius: 5px;4 unmodified linesalign-items: center;justify-content: space-between;overflow: hidden;cursor: pointer;}.box span {padding: 5px;font-size: 12px;letter-spacing: 1px;font-weight: 500;}/*Hover-Section*/.box:hover, .box:hover+ul li .box {background: var(--primary-500);}.box:hover+ul li::after, .box:hover+ul li::before, .box:hover+ul::before, .box:hover+ul ul::before, .box:hover+ul .box::before {border-color: var(--primary-500);}.chosen-token {15 unmodified lines.nonselected-sequence {background-color: var(--primary-500);}.nomargin {padding-left: 0!important;}"""36 unmodified linesselected_class = "selected-sequence"else:selected_class = "nonselected-sequence"return f"<li> <div class='box end-of-text child {selected_class}'> <span> <b>{clean(token)}</b> <br>Total score: {node.total_score:.2f}</span> </div> </li>"html_content = (f"<li> <div class='box nonfinal child'> <span> <b>{clean(token)}</b> </span>")if node.table is not None:html_content += node.tablehtml_content += "</div>"if len(node.children.keys()) > 0:html_content += "<ul> "7 unmodified linesdef generate_html(start_sentence, original_tree):html_output = f"""<div class="custom-container"><div class="tree"> <ul class="nomargin"><li class="nomargin"><div class="box" id='root'> <span> <b>{start_sentence}</b> </span> {original_tree.table} </div>"""html_output += "<ul> "for subnode in original_tree.children.values():html_output += generate_nodes(subnode, step=1)html_output += "</ul>"html_output += """</li></ul></div></div>"""return html_output16 unmodified linesis_selected_sequence: booldef generate_beams(start_sentence, scores, length_penalty, decoded_sequences):input_length = len(tokenizer([start_sentence], return_tensors="pt"))original_tree = BeamNode(cumulative_score=0,10 unmodified linesbeam_trees = [original_tree] * n_beamsfor step, step_scores in enumerate(scores):(top_token_indexes,top_cumulative_scores,1 unmodified linecurrent_sequence,top_tokens,) = ([], [], [], [], [])for beam_ix in range(n_beams): # Get possible descendants for each beamcurrent_beam = beam_trees[beam_ix]# skip if the beam is already final13 unmodified linescurrent_sequence += [beam_trees[beam_ix].current_sequence] * n_beamstop_tokens += [tokenizer.decode([el]) for el in current_top_token_indexes]top_df = pd.DataFrame.from_dict({"token_index": top_token_indexes,13 unmodified linestop_df_selected = top_df.sort_values("cumulative_score", ascending=False).iloc[:n_beams]# Write the scores table - one per beam sourcefor beam_ix in reversed(list(range(n_beams))):10 unmodified lines)beam_trees[beam_ix].table = markdown_table# Add new children for each beamcumulative_scores = [beam.cumulative_score for beam in beam_trees]for beam_ix in range(n_beams):current_token_choice_ix = top_df_selected.iloc[beam_ix]["token_index"]current_token_choice = tokenizer.decode([current_token_choice_ix])# Update the source treesource_beam_ix = int(top_df_selected.iloc[beam_ix]["beam_index"])cumulative_score = (cumulative_scores[source_beam_ix]2 unmodified linescurrent_sequence = (beam_trees[source_beam_ix].current_sequence + current_token_choice)beam_trees[source_beam_ix].children[current_token_choice_ix] = BeamNode(current_token_ix=current_token_choice_ix,table=None,13 unmodified lines),)# Reassign all beams at oncebeam_trees = [beam_trees[int(top_df_selected.iloc[beam_ix]["beam_index"])]for beam_ix in range(n_beams)6 unmodified linesreturn original_tree@spaces.GPUdef get_beam_search_html(input_text, number_steps, number_beams, length_penalty, num_return_sequences25 unmodified linesoutputs.scores[:],length_penalty,decoded_sequences,)html = generate_html(input_text, original_tree)return html, markdown28 unmodified lines)text = gr.Textbox(label="Sentence to decode from",value="Conclusion: thanks a lot. This article was originally published on",)with gr.Row():n_steps = gr.Slider(129 unmodified lines1301311321331341351364 unmodified lines14114214314414514614714814915015115215315415515615715815 unmodified lines17417517617717817936 unmodified lines2162172182192202212222232242252262272282297 unmodified lines23723823924024124224324424524624724824925025125216 unmodified lines26927027127227327427510 unmodified lines2862872882892902912922931 unmodified line29529629729829930030113 unmodified lines31531631731831932013 unmodified lines33433533633733833934034134210 unmodified lines3533543553563573583593603613623633643652 unmodified lines36836937037137237337437537613 unmodified lines3903913923933943953963976 unmodified lines40440540640740840925 unmodified lines43543643743843944044128 unmodified lines470471472473474475476129 unmodified linesmargin-top: -5px;transform: rotate(315deg);}.tree li a {border: 1px solid var(--body-text-color);padding: 5px;border-radius: 5px;4 unmodified linesalign-items: center;justify-content: space-between;overflow: hidden;}.tree li a span {padding: 5px;font-size: 12px;letter-spacing: 1px;font-weight: 500;}/*Hover-Section*/.tree li a:hover, .tree li a:hover+ul li a {background: var(--primary-500);}.tree li a:hover+ul li::after, .tree li a:hover+ul li::before, .tree li a:hover+ul::before, .tree li a:hover+ul ul::before, .tree li a:hover+ul a::before {border-color: var(--primary-500);}.chosen-token {15 unmodified lines.nonselected-sequence {background-color: var(--primary-500);}"""36 unmodified linesselected_class = "selected-sequence"else:selected_class = "nonselected-sequence"return f"<li> <a href='#' class='end-of-text child {selected_class}'> <span> <b>{clean(token)}</b> <br>Total score: {node.total_score:.2f}</span> </a> </li>"html_content = (f"<li> <a href='#' class='nonfinal child'> <span> <b>{clean(token)}</b> </span>")if node.table is not None:html_content += node.tablehtml_content += "</a>"if len(node.children.keys()) > 0:html_content += "<ul> "7 unmodified linesdef generate_html(start_sentence, original_tree):html_output = f"""<div class="custom-container"><div class="tree"><ul> <li> <a href='#' id='root'> <span> <b>{start_sentence}</b> </span> {original_tree.table} </a>"""html_output += "<ul> "for subnode in original_tree.children.values():html_output += generate_nodes(subnode, step=1)html_output += "</ul>"html_output += """</li> </ul></div></body>"""return html_output16 unmodified linesis_selected_sequence: booldef generate_beams(start_sentence, scores, length_penalty, decoded_sequences, beam_indexes_source):input_length = len(tokenizer([start_sentence], return_tensors="pt"))original_tree = BeamNode(cumulative_score=0,10 unmodified linesbeam_trees = [original_tree] * n_beamsfor step, step_scores in enumerate(scores):# Gather all possible descendants for each beam(top_token_indexes,top_cumulative_scores,1 unmodified linecurrent_sequence,top_tokens,) = ([], [], [], [], [])for beam_ix in range(n_beams):current_beam = beam_trees[beam_ix]# skip if the beam is already final13 unmodified linescurrent_sequence += [beam_trees[beam_ix].current_sequence] * n_beamstop_tokens += [tokenizer.decode([el]) for el in current_top_token_indexes]top_df = pd.DataFrame.from_dict({"token_index": top_token_indexes,13 unmodified linestop_df_selected = top_df.sort_values("cumulative_score", ascending=False).iloc[:n_beams]if any(["you enjoyed" in el for el in top_df["current_sequence"]]):print("Displaying debug info:::")display(top_df_selected)# Write the scores table - one per beam sourcefor beam_ix in reversed(list(range(n_beams))):10 unmodified lines)beam_trees[beam_ix].table = markdown_table# Add new children to each beamcumulative_scores = [beam.cumulative_score for beam in beam_trees]for _, row in top_df_selected.iterrows():# Update the source treesource_beam_ix = int(row["beam_index"])current_token_choice_ix = row["token_index"]current_token_choice = tokenizer.decode([current_token_choice_ix])cumulative_score = (cumulative_scores[source_beam_ix]2 unmodified linescurrent_sequence = (beam_trees[source_beam_ix].current_sequence + current_token_choice)if current_token_choice_ix == 340:print("Found info:")print(f"We generate token '{current_token_choice}', and the total sequence is '{current_sequence}'")beam_trees[source_beam_ix].children[current_token_choice_ix] = BeamNode(current_token_ix=current_token_choice_ix,table=None,13 unmodified lines),)# Swap all beams by descending cumul score, so that n°1 has the highest cumulative score, and so onbeam_trees = [beam_trees[int(top_df_selected.iloc[beam_ix]["beam_index"])]for beam_ix in range(n_beams)6 unmodified linesreturn original_tree@spaces.GPUdef get_beam_search_html(input_text, number_steps, number_beams, length_penalty, num_return_sequences25 unmodified linesoutputs.scores[:],length_penalty,decoded_sequences,outputs.beam_indices,)html = generate_html(input_text, original_tree)return html, markdown28 unmodified lines)text = gr.Textbox(label="Sentence to decode from",value="Conclusion: thanks a lot. That's all for today",)with gr.Row():n_steps = gr.Slider(
app.py+31-27