Skip to content

Instantly share code, notes, and snippets.

@vgel
Last active July 18, 2024 08:10
Show Gist options
  • Save vgel/c91d01265d01dbe34abbbe1372465d79 to your computer and use it in GitHub Desktop.
Save vgel/c91d01265d01dbe34abbbe1372465d79 to your computer and use it in GitHub Desktop.
generating a language response vector w/ repeng
import json
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from repeng import ControlVector, ControlModel, DatasetEntry
model_name = "mistralai/Mistral-7B-Instruct-v0.1"
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token_id = 0
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16)
model = model.to("cuda:0" if torch.cuda.is_available() else "mps:0" if torch.backends.mps.is_available() else "cpu")
model = ControlModel(model, list(range(-5, -18, -1)))
user_tag, asst_tag = "[INST]", "[/INST]"
def generate_with_vector(
input: str,
vector: ControlVector,
coeffs: tuple[float, float],
max_new_tokens: int = 128,
repetition_penalty: float = 1.1,
show_baseline: bool = True,
):
positive_coeff, negative_coeff = coeffs
assert positive_coeff > 0
assert negative_coeff < 0
if user_tag not in input:
input = f"{user_tag} {input.strip()} {asst_tag}"
input_ids = tokenizer(input, return_tensors="pt").to(model.device)
settings = {
"pad_token_id": tokenizer.eos_token_id, # silence warning
"do_sample": True,
"temperature": 0.7,
"max_new_tokens": max_new_tokens,
"repetition_penalty": repetition_penalty,
}
if show_baseline:
print("==baseline ---------------------------------------------------")
model.reset()
print(tokenizer.decode(model.generate(**input_ids, **settings).squeeze()).strip())
print("\n++control ---------------------------------------------------")
model.set_control(vector, positive_coeff)
print(tokenizer.decode(model.generate(**input_ids, **settings).squeeze()).strip())
print("\n--control ---------------------------------------------------")
model.set_control(vector, negative_coeff)
print(tokenizer.decode(model.generate(**input_ids, **settings).squeeze()).strip())
model.reset()
with open("data/english_spanish.json") as f:
english_spanish_dataset = []
for q in json.load(f):
question, ans_eng, ans_spn = q["question"], q["answer"], q["answer_spanish"]
ans_eng_tok, ans_spn_tok = tokenizer.tokenize(ans_eng), tokenizer.tokenize(ans_spn)
for i in range(5, min(len(ans_eng_tok), len(ans_spn_tok))):
# bit of length-based data augmentation to make up for our small training set
ans_eng_trunc = tokenizer.convert_tokens_to_string(ans_eng_tok[:i])
ans_spn_trunc = tokenizer.convert_tokens_to_string(ans_spn_tok[:i])
english_spanish_dataset.append(DatasetEntry(
positive=f"[INST] {question} [/INST] {ans_spn_trunc}",
negative=f"[INST] {question} [/INST] {ans_eng_trunc}",
))
model.reset()
english_spanish_vector = ControlVector.train(model, tokenizer, english_spanish_dataset, method="pca_center")
# 100%|██████████| 134/134 [00:32<00:00, 4.08it/s]
# 100%|██████████| 31/31 [01:06<00:00, 2.16s/it]
# Prefill with a single ¡ to make it a bit more reliable--
# you might be able to get away with just prefilling the language's equivalent of "definitely!" or whatever
# and not using a vector at all. but as you can see both together are better than either alone
generate_with_vector(
"[INST] How do I cook eggs? [/INST] ¡",
english_spanish_vector,
(1, -1),
max_new_tokens=64,
# repetition_penalty=1.3,
)
# ==baseline ---------------------------------------------------
# <s> [INST] How do I cook eggs? [/INST] ¡Hola! Eggs are a versatile and delicious ingredient that you can enjoy in many different ways. Here are some simple methods to cook eggs:
#
# 1. **Boiled Eggs**: Fill a saucepan with water, bring it to a boil, then reduce the heat to medium.
#
# ++control ---------------------------------------------------
# <s> [INST] How do I cook eggs? [/INST] ¡Bienvenido a la cocina! En este momento, vamos a aprender a cocinar aguantantes en los diferentesos métodos que existen para cocinar aguantantes; sabrá cómo hacer aguantantes fritos, en caliente, crujientes
#
# --control ---------------------------------------------------
# <s> [INST] How do I cook eggs? [/INST] ¡Hello! Eggs are a versatile and nutritious food. Here are some basic methods to cook eggs:
#
# 1. Boiled: You can boil eggs on the stove or in the oven. For a simple st boiled egg, place it in a saucepan with water, then cook it
[
{
"question": "What's the capital of France?",
"answer": "The capital of France is Paris.",
"answer_spanish": "La capital de Francia es París."
},
{
"question": "How do I make scrambled eggs?",
"answer": "Beat eggs, cook in a buttered pan over medium heat while stirring until set.",
"answer_spanish": "Bata los huevos, cocine en una sartén con mantequilla a fuego medio mientras revuelve hasta que cuajen."
},
{
"question": "What's the difference between a virus and a bacterium?",
"answer": "Viruses are smaller and require a host to reproduce, while bacteria are larger and can reproduce on their own.",
"answer_spanish": "Los virus son más pequeños y requieren un huésped para reproducirse, mientras que las bacterias son más grandes y pueden reproducirse por sí mismas."
},
{
"question": "Who wrote 'To Kill a Mockingbird'?",
"answer": "Harper Lee wrote 'To Kill a Mockingbird'.",
"answer_spanish": "Harper Lee escribió 'Matar a un ruiseñor'."
},
{
"question": "What's the formula for calculating the area of a circle?",
"answer": "The formula for a circle's area is A = πr², where r is the radius.",
"answer_spanish": "La fórmula para el área de un círculo es A = πr², donde r es el radio."
},
{
"question": "How can I improve my time management skills?",
"answer": "Prioritize tasks, use a planner, set deadlines, and minimize distractions.",
"answer_spanish": "Priorice tareas, use un planificador, establezca plazos y minimice las distracciones."
},
{
"question": "What causes earthquakes?",
"answer": "Earthquakes are caused by the movement of tectonic plates in the Earth's crust.",
"answer_spanish": "Los terremotos son causados por el movimiento de las placas tectónicas en la corteza terrestre."
},
{
"question": "How do I change a flat tire?",
"answer": "Loosen lug nuts, jack up the car, remove old tire, put on spare, and tighten lug nuts.",
"answer_spanish": "Afloje las tuercas, levante el auto con el gato, quite el neumático viejo, coloque el de repuesto y apriete las tuercas."
},
{
"question": "What's the difference between HTTP and HTTPS?",
"answer": "HTTPS is a secure version of HTTP that encrypts data transmission between a browser and a website.",
"answer_spanish": "HTTPS es una versión segura de HTTP que cifra la transmisión de datos entre un navegador y un sitio web."
},
{
"question": "How does photosynthesis work?",
"answer": "Plants use sunlight, water, and CO2 to produce glucose and oxygen.",
"answer_spanish": "Las plantas usan luz solar, agua y CO2 para producir glucosa y oxígeno."
},
{
"question": "What's the largest planet in our solar system?",
"answer": "Jupiter is the largest planet in our solar system.",
"answer_spanish": "Júpiter es el planeta más grande de nuestro sistema solar."
},
{
"question": "How do I create a strong password?",
"answer": "Use a mix of uppercase and lowercase letters, numbers, and symbols, and make it at least 12 characters long.",
"answer_spanish": "Use una mezcla de letras mayúsculas y minúsculas, números y símbolos, y hágala de al menos 12 caracteres de longitud."
},
{
"question": "What's the difference between weather and climate?",
"answer": "Weather is short-term atmospheric conditions, while climate is the average weather patterns over a long period.",
"answer_spanish": "El tiempo son las condiciones atmosféricas a corto plazo, mientras que el clima es el patrón promedio del tiempo a largo plazo."
},
{
"question": "How do I calculate percentages?",
"answer": "To calculate a percentage, divide the part by the whole and multiply by 100.",
"answer_spanish": "Para calcular un porcentaje, divida la parte por el todo y multiplique por 100."
},
{
"question": "What's the function of the liver?",
"answer": "The liver filters blood, produces bile, stores energy, and helps process nutrients.",
"answer_spanish": "El hígado filtra la sangre, produce bilis, almacena energía y ayuda a procesar nutrientes."
},
{
"question": "How do I start a garden?",
"answer": "Choose a sunny spot, prepare the soil, select plants suitable for your climate, and water regularly.",
"answer_spanish": "Elija un lugar soleado, prepare el suelo, seleccione plantas adecuadas para su clima y riegue regularmente."
},
{
"question": "What's the difference between a simile and a metaphor?",
"answer": "A simile compares using 'like' or 'as', while a metaphor directly states one thing is another.",
"answer_spanish": "Un símil compara usando 'como', mientras que una metáfora afirma directamente que una cosa es otra."
},
{
"question": "How does a refrigerator work?",
"answer": "A refrigerator uses a cooling cycle to remove heat from inside, keeping the contents cold.",
"answer_spanish": "Un refrigerador usa un ciclo de enfriamiento para eliminar el calor del interior, manteniendo fríos los contenidos."
},
{
"question": "What's the difference between RAM and ROM?",
"answer": "RAM is temporary, volatile memory for active processes, while ROM is permanent, non-volatile storage for essential data.",
"answer_spanish": "La RAM es memoria temporal y volátil para procesos activos, mientras que la ROM es almacenamiento permanente y no volátil para datos esenciales."
},
{
"question": "How do I tie a tie?",
"answer": "Drape around neck, cross wide end over narrow, bring up through loop, down through knot, and tighten.",
"answer_spanish": "Coloque alrededor del cuello, cruce el extremo ancho sobre el estrecho, páselo hacia arriba por el lazo, hacia abajo por el nudo y ajuste."
},
{
"question": "What's the Pythagorean theorem?",
"answer": "In a right triangle, the square of the hypotenuse equals the sum of squares of the other two sides.",
"answer_spanish": "En un triángulo rectángulo, el cuadrado de la hipotenusa es igual a la suma de los cuadrados de los otros dos lados."
},
{
"question": "How do I improve my public speaking skills?",
"answer": "Practice regularly, know your audience, use visual aids, and focus on body language and voice modulation.",
"answer_spanish": "Practique regularmente, conozca a su audiencia, use ayudas visuales y concéntrese en el lenguaje corporal y la modulación de la voz."
},
{
"question": "What's the difference between a crocodile and an alligator?",
"answer": "Crocodiles have V-shaped snouts and visible lower teeth, while alligators have U-shaped snouts and only upper teeth visible when mouth is closed.",
"answer_spanish": "Los cocodrilos tienen hocicos en forma de V y dientes inferiores visibles, mientras que los caimanes tienen hocicos en forma de U y solo los dientes superiores son visibles cuando la boca está cerrada."
},
{
"question": "How do I create a budget?",
"answer": "Track income and expenses, categorize spending, set financial goals, and allocate funds accordingly.",
"answer_spanish": "Rastree ingresos y gastos, categorice los gastos, establezca metas financieras y asigne fondos en consecuencia."
},
{
"question": "What's the difference between a tornado and a hurricane?",
"answer": "Tornadoes are narrow, violent windstorms over land, while hurricanes are large, rotating storms that form over warm ocean waters.",
"answer_spanish": "Los tornados son tormentas de viento estrechas y violentas sobre tierra, mientras que los huracanes son tormentas grandes y giratorias que se forman sobre aguas oceánicas cálidas."
},
{
"question": "How do I perform CPR?",
"answer": "Check for response, call for help, start chest compressions, give rescue breaths if trained, and continue until help arrives.",
"answer_spanish": "Verifique la respuesta, pida ayuda, inicie compresiones torácicas, dé respiraciones de rescate si está entrenado y continúe hasta que llegue la ayuda."
},
{
"question": "What's the difference between a democracy and a republic?",
"answer": "In a democracy, people vote directly on laws, while in a republic, they elect representatives to make laws on their behalf.",
"answer_spanish": "En una democracia, la gente vota directamente sobre las leyes, mientras que en una república, eligen representantes para que hagan leyes en su nombre."
},
{
"question": "How do I remove a stain from a carpet?",
"answer": "Blot the stain, apply a cleaning solution, work from the outside in, and rinse with clean water.",
"answer_spanish": "Seque la mancha, aplique una solución de limpieza, trabaje desde el exterior hacia el interior y enjuague con agua limpia."
},
{
"question": "What's the difference between a fruit and a vegetable?",
"answer": "Botanically, fruits contain seeds and develop from flowers, while vegetables are other edible parts of plants.",
"answer_spanish": "Botánicamente, las frutas contienen semillas y se desarrollan a partir de flores, mientras que las verduras son otras partes comestibles de las plantas."
},
{
"question": "How do I improve my posture?",
"answer": "Keep your shoulders back, chin tucked, and core engaged, and take frequent breaks from sitting.",
"answer_spanish": "Mantenga los hombros hacia atrás, la barbilla metida y el core activado, y tome descansos frecuentes de estar sentado."
},
{
"question": "What's the difference between IPv4 and IPv6?",
"answer": "IPv4 uses 32-bit addresses, while IPv6 uses 128-bit addresses, allowing for many more unique IP addresses.",
"answer_spanish": "IPv4 usa direcciones de 32 bits, mientras que IPv6 usa direcciones de 128 bits, permitiendo muchas más direcciones IP únicas."
},
{
"question": "How do I start meditating?",
"answer": "Find a quiet space, sit comfortably, focus on your breath, and gently redirect your thoughts when they wander.",
"answer_spanish": "Encuentre un espacio tranquilo, siéntese cómodamente, concéntrese en su respiración y redirija suavemente sus pensamientos cuando se dispersen."
},
{
"question": "What's the difference between a recession and a depression?",
"answer": "A recession is a period of economic decline lasting months, while a depression is a severe, long-term downturn lasting years.",
"answer_spanish": "Una recesión es un período de declive económico que dura meses, mientras que una depresión es una caída severa y a largo plazo que dura años."
},
{
"question": "How do I change a lightbulb?",
"answer": "Turn off the power, wait for the bulb to cool, unscrew the old bulb, and screw in the new one.",
"answer_spanish": "Apague la energía, espere a que la bombilla se enfríe, desenrosque la bombilla vieja y enrosque la nueva."
},
{
"question": "What's the difference between a galaxy and a solar system?",
"answer": "A galaxy is a vast collection of stars, while a solar system is a star and the planets orbiting it.",
"answer_spanish": "Una galaxia es una vasta colección de estrellas, mientras que un sistema solar es una estrella y los planetas que la orbitan."
},
{
"question": "How do I make compost?",
"answer": "Mix green materials like food scraps with brown materials like leaves, keep moist, and turn regularly.",
"answer_spanish": "Mezcle materiales verdes como restos de comida con materiales marrones como hojas, manténgalo húmedo y voltee regularmente."
},
{
"question": "What's the difference between a credit card and a debit card?",
"answer": "A credit card borrows money from the issuer, while a debit card draws directly from your bank account.",
"answer_spanish": "Una tarjeta de crédito toma prestado dinero del emisor, mientras que una tarjeta de débito extrae directamente de su cuenta bancaria."
},
{
"question": "How do I improve my vocabulary?",
"answer": "Read widely, use a dictionary, learn word roots, and practice using new words in context.",
"answer_spanish": "Lea ampliamente, use un diccionario, aprenda raíces de palabras y practique usando nuevas palabras en contexto."
},
{
"question": "What's the difference between a tornado watch and a tornado warning?",
"answer": "A tornado watch means conditions are favorable for tornadoes, while a warning means a tornado has been sighted or indicated by weather radar.",
"answer_spanish": "Una vigilancia de tornado significa que las condiciones son favorables para tornados, mientras que una advertencia significa que se ha avistado un tornado o se ha indicado por radar meteorológico."
},
{
"question": "How do I perform the Heimlich maneuver?",
"answer": "Stand behind the person, wrap your arms around their waist, make a fist above their navel, and give quick upward thrusts.",
"answer_spanish": "Párese detrás de la persona, rodee su cintura con sus brazos, haga un puño por encima de su ombligo y dé empujones rápidos hacia arriba."
},
{
"question": "What's the difference between a mammal and a reptile?",
"answer": "Mammals are warm-blooded and have hair, while reptiles are cold-blooded and have scales.",
"answer_spanish": "Los mamíferos son de sangre caliente y tienen pelo, mientras que los reptiles son de sangre fría y tienen escamas."
},
{
"question": "How do I make a paper airplane?",
"answer": "Fold a sheet of paper in half lengthwise, unfold, fold corners to center, fold in half, and fold wings down.",
"answer_spanish": "Doble una hoja de papel por la mitad a lo largo, desdoble, doble las esquinas hacia el centro, doble por la mitad y doble las alas hacia abajo."
},
{
"question": "What's the difference between a hurricane and a typhoon?",
"answer": "Hurricanes and typhoons are the same type of storm, but occur in different parts of the world.",
"answer_spanish": "Los huracanes y los tifones son el mismo tipo de tormenta, pero ocurren en diferentes partes del mundo."
},
{
"question": "How do I build muscle?",
"answer": "Lift weights regularly, increase resistance over time, eat a protein-rich diet, and get adequate rest.",
"answer_spanish": "Levante pesas regularmente, aumente la resistencia con el tiempo, consuma una dieta rica en proteínas y descanse adecuadamente."
},
{
"question": "What's the difference between a verb and a noun?",
"answer": "A verb describes an action or state, while a noun names a person, place, thing, or idea.",
"answer_spanish": "Un verbo describe una acción o estado, mientras que un sustantivo nombra una persona, lugar, cosa o idea."
},
{
"question": "How do I change a car's oil?",
"answer": "Drain old oil, replace oil filter, add new oil, and dispose of old oil properly.",
"answer_spanish": "Drene el aceite viejo, reemplace el filtro de aceite, agregue aceite nuevo y deseche el aceite viejo adecuadamente."
},
{
"question": "What's the difference between mass and weight?",
"answer": "Mass is the amount of matter in an object, while weight is the force of gravity on that object.",
"answer_spanish": "La masa es la cantidad de materia en un objeto, mientras que el peso es la fuerza de la gravedad sobre ese objeto."
},
{
"question": "How do I write a resume?",
"answer": "Include contact info, work experience, education, skills, and tailor it to the job you're applying for.",
"answer_spanish": "Incluya información de contacto, experiencia laboral, educación, habilidades y adáptelo al trabajo al que está aplicando."
},
{
"question": "What's the difference between a tornado and a cyclone?",
"answer": "A tornado is a violent, rotating column of air, while a cyclone is a larger storm system with a low-pressure center.",
"answer_spanish": "Un tornado es una columna de aire violenta y giratoria, mientras que un ciclón es un sistema de tormenta más grande con un centro de baja presión."
},
{
"question": "How do I bake a cake?",
"answer": "Mix dry and wet ingredients separately, combine, pour into a pan, and bake at the specified temperature.",
"answer_spanish": "Mezcle los ingredientes secos y húmedos por separado, combínelos, vierta en un molde y hornee a la temperatura especificada."
},
{
"question": "What's the difference between socialism and communism?",
"answer": "Socialism advocates for communal control of production, while communism seeks a classless society with common ownership of all property.",
"answer_spanish": "El socialismo aboga por el control comunal de la producción, mientras que el comunismo busca una sociedad sin clases con propiedad común de todos los bienes."
},
{
"question": "How do I improve my memory?",
"answer": "Get enough sleep, exercise regularly, eat a healthy diet, and practice memory techniques like visualization.",
"answer_spanish": "Duerma lo suficiente, haga ejercicio regularmente, coma una dieta saludable y practique técnicas de memoria como la visualización."
},
{
"question": "What's the difference between a tornado watch and a tornado warning?",
"answer": "A tornado watch means conditions are favorable for tornadoes, while a warning means a tornado has been sighted or indicated by weather radar.",
"answer_spanish": "Una vigilancia de tornado significa que las condiciones son favorables para tornados, mientras que una advertencia significa que se ha avistado un tornado o se ha indicado por radar meteorológico."
},
{
"question": "How do I start a small business?",
"answer": "Develop a business plan, secure funding, choose a business structure, register your business, and obtain necessary licenses and permits.",
"answer_spanish": "Desarrolle un plan de negocios, obtenga financiamiento, elija una estructura empresarial, registre su negocio y obtenga las licencias y permisos necesarios."
},
{
"question": "What's the difference between a programming language and a markup language?",
"answer": "A programming language is used to create executable programs, while a markup language is used to format and structure documents.",
"answer_spanish": "Un lenguaje de programación se usa para crear programas ejecutables, mientras que un lenguaje de marcado se usa para formatear y estructurar documentos."
},
{
"question": "How do I learn a new language?",
"answer": "Practice regularly, immerse yourself in the language, use language learning apps, and try to converse with native speakers.",
"answer_spanish": "Practique regularmente, sumérjase en el idioma, use aplicaciones de aprendizaje de idiomas e intente conversar con hablantes nativos."
},
{
"question": "What's the difference between a monarchy and a dictatorship?",
"answer": "A monarchy is ruled by a hereditary sovereign, while a dictatorship is ruled by an individual who has seized power.",
"answer_spanish": "Una monarquía es gobernada por un soberano hereditario, mientras que una dictadura es gobernada por un individuo que ha tomado el poder."
},
{
"question": "How do I change a car tire?",
"answer": "Loosen lug nuts, jack up the car, remove the flat tire, put on the spare, and tighten the lug nuts.",
"answer_spanish": "Afloje las tuercas, levante el auto con el gato, quite el neumático pinchado, coloque el de repuesto y apriete las tuercas."
},
{
"question": "What's the difference between a comet and an asteroid?",
"answer": "Comets are made of ice and dust and have tails, while asteroids are rocky or metallic and don't have tails.",
"answer_spanish": "Los cometas están hechos de hielo y polvo y tienen colas, mientras que los asteroides son rocosos o metálicos y no tienen colas."
},
{
"question": "How do I create a website?",
"answer": "Choose a domain name, select a web hosting service, design your site, add content, and publish it online.",
"answer_spanish": "Elija un nombre de dominio, seleccione un servicio de alojamiento web, diseñe su sitio, agregue contenido y publíquelo en línea."
},
{
"question": "What's the difference between a hurricane and a typhoon?",
"answer": "Hurricanes and typhoons are the same type of storm, but occur in different parts of the world.",
"answer_spanish": "Los huracanes y los tifones son el mismo tipo de tormenta, pero ocurren en diferentes partes del mundo."
},
{
"question": "How do I improve my credit score?",
"answer": "Pay bills on time, reduce credit card balances, don't close old accounts, and avoid applying for new credit too often.",
"answer_spanish": "Pague las facturas a tiempo, reduzca los saldos de las tarjetas de crédito, no cierre cuentas antiguas y evite solicitar crédito nuevo con demasiada frecuencia."
},
{
"question": "What's the difference between a symphony and a concerto?",
"answer": "A symphony is a large-scale work for orchestra, while a concerto features a solo instrument with orchestral accompaniment.",
"answer_spanish": "Una sinfonía es una obra a gran escala para orquesta, mientras que un concierto presenta un instrumento solista con acompañamiento orquestal."
},
{
"question": "How do I train a dog?",
"answer": "Use positive reinforcement, be consistent, start with basic commands, and practice regularly.",
"answer_spanish": "Use refuerzo positivo, sea consistente, comience con comandos básicos y practique regularmente."
},
{
"question": "What's the difference between a virus and a bacterial infection?",
"answer": "Viruses are smaller and can't survive without a host, while bacteria are larger and can survive on their own.",
"answer_spanish": "Los virus son más pequeños y no pueden sobrevivir sin un huésped, mientras que las bacterias son más grandes y pueden sobrevivir por sí mismas."
},
{
"question": "How do I perform CPR?",
"answer": "Call for help, start chest compressions, give rescue breaths if trained, and continue until professional help arrives.",
"answer_spanish": "Pida ayuda, inicie compresiones torácicas, dé respiraciones de rescate si está entrenado y continúe hasta que llegue la ayuda profesional."
},
{
"question": "What's the difference between weather and climate?",
"answer": "Weather is the day-to-day state of the atmosphere, while climate is the average weather conditions over a long period.",
"answer_spanish": "El tiempo es el estado diario de la atmósfera, mientras que el clima es el promedio de las condiciones meteorológicas durante un largo período."
},
{
"question": "How do I make a budget?",
"answer": "Track income and expenses, set financial goals, allocate funds to different categories, and review regularly.",
"answer_spanish": "Rastree ingresos y gastos, establezca metas financieras, asigne fondos a diferentes categorías y revise regularmente."
},
{
"question": "What's the difference between a tsunami and a tidal wave?",
"answer": "A tsunami is caused by seismic activity, while a tidal wave is caused by the gravitational forces of the moon and sun.",
"answer_spanish": "Un tsunami es causado por actividad sísmica, mientras que una marea es causada por las fuerzas gravitacionales de la luna y el sol."
},
{
"question": "How do I write a cover letter?",
"answer": "Address the hiring manager, highlight relevant skills and experience, show enthusiasm for the role, and close with a call to action.",
"answer_spanish": "Diríjase al gerente de contratación, destaque habilidades y experiencia relevantes, muestre entusiasmo por el puesto y cierre con una llamada a la acción."
},
{
"question": "What's the difference between a recession and a depression?",
"answer": "A recession is a period of economic decline lasting months, while a depression is a severe, long-term downturn lasting years.",
"answer_spanish": "Una recesión es un período de declive económico que dura meses, mientras que una depresión es una caída severa y a largo plazo que dura años."
},
{
"question": "How do I quit smoking?",
"answer": "Set a quit date, use nicotine replacement therapy, avoid triggers, and seek support from friends and family.",
"answer_spanish": "Fije una fecha para dejar de fumar, use terapia de reemplazo de nicotina, evite los desencadenantes y busque el apoyo de amigos y familiares."
},
{
"question": "What's the difference between a tornado and a waterspout?",
"answer": "A tornado forms over land, while a waterspout forms over water but is essentially the same phenomenon.",
"answer_spanish": "Un tornado se forma sobre tierra, mientras que una tromba marina se forma sobre el agua, pero es esencialmente el mismo fenómeno."
},
{
"question": "How do I start investing in stocks?",
"answer": "Open a brokerage account, research companies, diversify your portfolio, and consider starting with index funds.",
"answer_spanish": "Abra una cuenta de corretaje, investigue empresas, diversifique su cartera y considere comenzar con fondos indexados."
},
{
"question": "What's the difference between a college and a university?",
"answer": "Colleges typically offer undergraduate degrees, while universities offer both undergraduate and graduate programs.",
"answer_spanish": "Los colegios típicamente ofrecen títulos de pregrado, mientras que las universidades ofrecen programas tanto de pregrado como de posgrado."
},
{
"question": "How do I improve my singing voice?",
"answer": "Practice regularly, learn proper breathing techniques, stay hydrated, and consider taking voice lessons.",
"answer_spanish": "Practique regularmente, aprenda técnicas de respiración adecuadas, manténgase hidratado y considere tomar clases de canto."
},
{
"question": "What's the difference between a psychologist and a psychiatrist?",
"answer": "Psychologists focus on therapy and cannot prescribe medication, while psychiatrists are medical doctors who can prescribe medication.",
"answer_spanish": "Los psicólogos se enfocan en la terapia y no pueden recetar medicamentos, mientras que los psiquiatras son médicos que pueden recetar medicamentos."
},
{
"question": "How do I make a good first impression?",
"answer": "Dress appropriately, make eye contact, smile, use a firm handshake, and show genuine interest in the other person.",
"answer_spanish": "Vístase apropiadamente, haga contacto visual, sonría, use un apretón de manos firme y muestre un interés genuino en la otra persona."
},
{
"question": "What's the difference between a hurricane and a cyclone?",
"answer": "Hurricanes and cyclones are the same type of storm but occur in different regions of the world.",
"answer_spanish": "Los huracanes y los ciclones son el mismo tipo de tormenta pero ocurren en diferentes regiones del mundo."
},
{
"question": "How do I reduce stress?",
"answer": "Exercise regularly, practice mindfulness or meditation, get enough sleep, and maintain a healthy work-life balance.",
"answer_spanish": "Haga ejercicio regularmente, practique la atención plena o la meditación, duerma lo suficiente y mantenga un equilibrio saludable entre el trabajo y la vida personal."
},
{
"question": "What's the difference between a democracy and a republic?",
"answer": "In a democracy, people vote directly on laws, while in a republic, they elect representatives to make laws on their behalf.",
"answer_spanish": "En una democracia, la gente vota directamente sobre las leyes, mientras que en una república, eligen representantes para que hagan leyes en su nombre."
},
{
"question": "How do I improve my problem-solving skills?",
"answer": "Practice critical thinking, break problems into smaller parts, consider multiple solutions, and learn from past experiences.",
"answer_spanish": "Practique el pensamiento crítico, divida los problemas en partes más pequeñas, considere múltiples soluciones y aprenda de experiencias pasadas."
},
{
"question": "What's the difference between a hurricane watch and a hurricane warning?",
"answer": "A hurricane watch means hurricane conditions are possible, while a warning means hurricane conditions are expected.",
"answer_spanish": "Una vigilancia de huracán significa que las condiciones de huracán son posibles, mientras que una advertencia significa que se esperan condiciones de huracán."
},
{
"question": "How do I start a vegetable garden?",
"answer": "Choose a sunny location, prepare the soil, select appropriate plants for your climate, and water and fertilize regularly.",
"answer_spanish": "Elija una ubicación soleada, prepare el suelo, seleccione plantas apropiadas para su clima, y riegue y fertilice regularmente."
},
{
"question": "What's the difference between a lightning bolt and a thunderbolt?",
"answer": "A lightning bolt is the visible electrical discharge, while a thunderbolt refers to the sound produced by the lightning.",
"answer_spanish": "Un rayo es la descarga eléctrica visible, mientras que un trueno se refiere al sonido producido por el rayo."
},
{
"question": "How do I improve my critical thinking skills?",
"answer": "Question assumptions, evaluate evidence, consider alternative viewpoints, and practice logical reasoning.",
"answer_spanish": "Cuestione suposiciones, evalúe evidencias, considere puntos de vista alternativos y practique el razonamiento lógico."
},
{
"question": "What's the difference between a tornado and a derecho?",
"answer": "A tornado is a rotating column of air, while a derecho is a widespread, long-lived windstorm associated with a band of rapidly moving thunderstorms.",
"answer_spanish": "Un tornado es una columna de aire giratoria, mientras que un derecho es una tormenta de viento generalizada y de larga duración asociada con una banda de tormentas eléctricas que se mueven rápidamente."
},
{
"question": "How do I meditate?",
"answer": "Find a quiet space, sit comfortably, focus on your breath, and gently redirect your thoughts when they wander.",
"answer_spanish": "Encuentre un espacio tranquilo, siéntese cómodamente, concéntrese en su respiración y redirija suavemente sus pensamientos cuando se distraigan."
},
{
"question": "What's the difference between a hurricane and a tropical storm?",
"answer": "A hurricane has sustained winds of at least 74 mph, while a tropical storm has winds between 39-73 mph.",
"answer_spanish": "Un huracán tiene vientos sostenidos de al menos 74 mph, mientras que una tormenta tropical tiene vientos entre 39-73 mph."
},
{
"question": "How do I improve my listening skills?",
"answer": "Practice active listening, avoid interrupting, ask clarifying questions, and provide feedback to show understanding.",
"answer_spanish": "Practique la escucha activa, evite interrumpir, haga preguntas aclaratorias y proporcione retroalimentación para mostrar comprensión."
},
{
"question": "What's the difference between a solar eclipse and a lunar eclipse?",
"answer": "A solar eclipse occurs when the moon blocks the sun, while a lunar eclipse occurs when the Earth's shadow falls on the moon.",
"answer_spanish": "Un eclipse solar ocurre cuando la luna bloquea el sol, mientras que un eclipse lunar ocurre cuando la sombra de la Tierra cae sobre la luna."
},
{
"question": "How do I create a strong password?",
"answer": "Use a mix of uppercase and lowercase letters, numbers, and symbols, and make it at least 12 characters long.",
"answer_spanish": "Use una mezcla de letras mayúsculas y minúsculas, números y símbolos, y hágala de al menos 12 caracteres de longitud."
},
{
"question": "What's the difference between a meteor and a meteorite?",
"answer": "A meteor is the flash of light we see in the sky, while a meteorite is the object that survives its fall through the atmosphere and lands on Earth.",
"answer_spanish": "Un meteoro es el destello de luz que vemos en el cielo, mientras que un meteorito es el objeto que sobrevive a su caída a través de la atmósfera y aterriza en la Tierra."
},
{
"question": "How do I improve my writing skills?",
"answer": "Read widely, write regularly, seek feedback, and study grammar and style guides.",
"answer_spanish": "Lea ampliamente, escriba regularmente, busque retroalimentación y estudie guías de gramática y estilo."
},
{
"question": "What's the difference between a hurricane and a typhoon?",
"answer": "Hurricanes and typhoons are the same type of storm, but they occur in different parts of the world.",
"answer_spanish": "Los huracanes y los tifones son el mismo tipo de tormenta, pero ocurren en diferentes partes del mundo."
},
{
"question": "How do I start running?",
"answer": "Start with a walk-run program, gradually increase distance and speed, invest in good shoes, and stay consistent.",
"answer_spanish": "Comience con un programa de caminar-correr, aumente gradualmente la distancia y la velocidad, invierta en buenos zapatos y manténgase constante."
},
{
"question": "What's the difference between a tornado watch and a tornado warning?",
"answer": "A tornado watch means conditions are favorable for tornadoes, while a warning means a tornado has been sighted or indicated by weather radar.",
"answer_spanish": "Una vigilancia de tornado significa que las condiciones son favorables para tornados, mientras que una advertencia significa que se ha avistado un tornado o se ha indicado por radar meteorológico."
},
{
"question": "How do I improve my public speaking skills?",
"answer": "Practice regularly, know your audience, use visual aids, and focus on body language and voice modulation.",
"answer_spanish": "Practique regularmente, conozca a su audiencia, use ayudas visuales y concéntrese en el lenguaje corporal y la modulación de la voz."
},
{
"question": "What's the difference between a tsunami and a tidal wave?",
"answer": "A tsunami is caused by seismic activity, while a tidal wave is caused by the gravitational forces of the moon and sun.",
"answer_spanish": "Un tsunami es causado por actividad sísmica, mientras que una marea es causada por las fuerzas gravitacionales de la luna y el sol."
},
{
"question": "How do I learn to code?",
"answer": "Choose a programming language, use online resources, practice coding regularly, and work on personal projects.",
"answer_spanish": "Elija un lenguaje de programación, use recursos en línea, practique la codificación regularmente y trabaje en proyectos personales."
},
{
"question": "What's the difference between a recession and a depression?",
"answer": "A recession is a period of economic decline lasting months, while a depression is a severe, long-term downturn lasting years.",
"answer_spanish": "Una recesión es un período de declive económico que dura meses, mientras que una depresión es una caída severa y a largo plazo que dura años."
},
{
"question": "How do I improve my time management skills?",
"answer": "Prioritize tasks, use a planner or digital calendar, minimize distractions, and learn to say no to non-essential commitments.",
"answer_spanish": "Priorice tareas, use un planificador o calendario digital, minimice las distracciones y aprenda a decir no a compromisos no esenciales."
},
{
"question": "What's the difference between a psychologist and a psychiatrist?",
"answer": "Psychologists focus on therapy and cannot prescribe medication, while psychiatrists are medical doctors who can prescribe medication.",
"answer_spanish": "Los psicólogos se enfocan en la terapia y no pueden recetar medicamentos, mientras que los psiquiatras son médicos que pueden recetar medicamentos."
},
{
"question": "How do I start a small business?",
"answer": "Develop a business plan, secure funding, choose a business structure, register your business, and obtain necessary licenses and permits.",
"answer_spanish": "Desarrolle un plan de negocios, obtenga financiamiento, elija una estructura empresarial, registre su negocio y obtenga las licencias y permisos necesarios."
},
{
"question": "What's the difference between a hurricane and a cyclone?",
"answer": "Hurricanes and cyclones are the same type of storm but occur in different regions of the world.",
"answer_spanish": "Los huracanes y los ciclones son el mismo tipo de tormenta pero ocurren en diferentes regiones del mundo."
},
{
"question": "How do I improve my memory?",
"answer": "Get enough sleep, exercise regularly, eat a healthy diet, and practice memory techniques like visualization and association.",
"answer_spanish": "Duerma lo suficiente, haga ejercicio regularmente, coma una dieta saludable y practique técnicas de memoria como la visualización y la asociación."
},
{
"question": "What's the difference between a tornado and a waterspout?",
"answer": "A tornado forms over land, while a waterspout forms over water but is essentially the same phenomenon.",
"answer_spanish": "Un tornado se forma sobre tierra, mientras que una tromba marina se forma sobre el agua, pero es esencialmente el mismo fenómeno."
},
{
"question": "How do I start investing in stocks?",
"answer": "Open a brokerage account, research companies, diversify your portfolio, and consider starting with index funds.",
"answer_spanish": "Abra una cuenta de corretaje, investigue empresas, diversifique su cartera y considere comenzar con fondos indexados."
},
{
"question": "What's the difference between a college and a university?",
"answer": "Colleges typically offer undergraduate degrees, while universities offer both undergraduate and graduate programs.",
"answer_spanish": "Los colegios típicamente ofrecen títulos de pregrado, mientras que las universidades ofrecen programas tanto de pregrado como de posgrado."
},
{
"question": "How do I improve my singing voice?",
"answer": "Practice regularly, learn proper breathing techniques, stay hydrated, and consider taking voice lessons.",
"answer_spanish": "Practique regularmente, aprenda técnicas de respiración adecuadas, manténgase hidratado y considere tomar clases de canto."
},
{
"question": "What's the difference between a democracy and a republic?",
"answer": "In a democracy, people vote directly on laws, while in a republic, they elect representatives to make laws on their behalf.",
"answer_spanish": "En una democracia, la gente vota directamente sobre las leyes, mientras que en una república, eligen representantes para que hagan leyes en su nombre."
},
{
"question": "How do I make a good first impression?",
"answer": "Dress appropriately, make eye contact, smile, use a firm handshake, and show genuine interest in the other person.",
"answer_spanish": "Vístase apropiadamente, haga contacto visual, sonría, use un apretón de manos firme y muestre un interés genuino en la otra persona."
},
{
"question": "What's the difference between a hurricane watch and a hurricane warning?",
"answer": "A hurricane watch means hurricane conditions are possible, while a warning means hurricane conditions are expected.",
"answer_spanish": "Una vigilancia de huracán significa que las condiciones de huracán son posibles, mientras que una advertencia significa que se esperan condiciones de huracán."
},
{
"question": "How do I reduce stress?",
"answer": "Exercise regularly, practice mindfulness or meditation, get enough sleep, and maintain a healthy work-life balance.",
"answer_spanish": "Haga ejercicio regularmente, practique la atención plena o la meditación, duerma lo suficiente y mantenga un equilibrio saludable entre el trabajo y la vida personal."
},
{
"question": "What's the difference between a lightning bolt and a thunderbolt?",
"answer": "A lightning bolt is the visible electrical discharge, while a thunderbolt refers to the sound produced by the lightning.",
"answer_spanish": "Un rayo es la descarga eléctrica visible, mientras que un trueno se refiere al sonido producido por el rayo."
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment